Skip to content

Instantly share code, notes, and snippets.

@Luehrsen
Created March 28, 2019 08:56
Show Gist options
  • Save Luehrsen/d47cdfa0fd9a58805cc179fdbd77176c to your computer and use it in GitHub Desktop.
Save Luehrsen/d47cdfa0fd9a58805cc179fdbd77176c to your computer and use it in GitHub Desktop.
Removes the block type on non-whitelisted post types
/**
* Removes the block type on non-whitelisted post types
*
* @param {Array} postTypeNames An array of post type names as white list for this block
* @param {string} blockName The name of the block
*
* @example
* limitBlockToPostType( [ 'page' ], 'core/paragraph' );
*
* @return {void}
*/
export const limitBlockToPostType = function( postTypeNames, blockName ) {
const comparePostType = ( selector, listener ) => {
let previousPostTypeState = selector();
return () => {
const currentPostTypeState = selector();
if ( currentPostTypeState && previousPostTypeState !== currentPostTypeState ) {
previousPostTypeState = currentPostTypeState;
listener( currentPostTypeState );
}
};
};
subscribe( comparePostType( select( 'core/editor' ).getCurrentPostType, ( postType ) => {
if ( postTypeNames.indexOf( postType ) === -1 ) {
wp.blocks.unregisterBlockType( blockName );
}
} ) );
};
@Luehrsen
Copy link
Author

Luehrsen commented Mar 28, 2019

We use this construct to handle a race condition. The block registry is being set up before the core/editor store so by the time we call registerBlockType we do not know yet on which post type we are. Thats why we subscribe to the store and once we get a non falsy response we check against an array of whitelisted post types. If the current post type is not in that array, we unregister the block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment