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”.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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