Pregunta

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".

¿Fue útil?

Solución

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'
                } );
            }
        }
    } );
} );
Licenciado bajo: CC-BY-SA con atribución
scroll top