Created
March 28, 2019 08:56
-
-
Save Luehrsen/d47cdfa0fd9a58805cc179fdbd77176c to your computer and use it in GitHub Desktop.
Removes the block type on non-whitelisted post types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 ); | |
} | |
} ) ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 callregisterBlockType
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.