Gutenberg. How To Register A Custom Block Style For Specific Post Type Only

Question

For the core/paragraph-Block, I would like to register a custom style. This is working fine with

const { registerBlockStyle } = wp.blocks;
wp.domReady( () => {
    registerBlockStyle( 'core/paragraph', {
        name: 'lead',
        label: 'Lead'
    } );
} );

Now I want this custom style to be applied only to certain post types, e.g. only to post type “post”. Therefor I have to access the current post type in the editor. But this is not working:

const { registerBlockStyle } = wp.blocks;
const { useSelect } = wp.data;

wp.domReady( () => {
    // This is not working:
    const postType = useSelect( select => select( 'core/editor').getCurrentPostType() );

    if ( postType === 'post' ) {

        registerBlockStyle( 'core/paragraph', {
            name: 'lead',
            label: 'Lead'
        } );
    }
} );

All I got is an React-minify-error in the console:

Invalid hook call. Hooks can only be called inside of the body of a function component.

I suppose I have to wrap everything into a component or something.

How can I make this working?

Alternative option

I could generate a separate javascript file which is only enqueued and loaded if the current post type is “post”.

0
uruk 1 month 2021-05-11T01:08:55-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse