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

The 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”.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

How can I make this working?

Not sure if there’s a better way, but I’d use subscribe() in the @wordpress/data package:

const { registerBlockStyle } = wp.blocks;
const { subscribe, select } = wp.data;

wp.domReady( () => {
    const unsubscribe = subscribe( () => {
        const postType = select( 'core/editor' ).getCurrentPostType();

        // 1. Unsubscribe once we've got the post type.
        if ( postType ) {
            unsubscribe();
            console.log( `Post type: ${ postType }. Unsubscribed.` );

            // 2. Register the block style if the post type is 'post'.
            if ( 'post' === postType ) {
                registerBlockStyle( 'core/paragraph', {
                        name: 'lead',
                        label: 'Lead'
                } );
            }
        }
    } );
} );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment