WordPress.org

WordPress Developer Blog

Snippet: Conditionally unregister patterns

Snippet: Conditionally unregister patterns

Have you ever run into a situation where you needed to unregister a block pattern in your theme? There may be many scenarios where you’d do this, but one of my primary reasons is to hide the “Your site doesn’t include support for the [Block Name] block” message from users when a pattern contains an unregistered block.

Use this PHP snippet to unregister patterns when specific blocks are unavailable. Just add the block names you want to test against as keys for the $maybe_unregister array with the pattern slugs as the values.

add_action( 'init', 'devblog_unregister_patterns', 999 );

function devblog_unregister_patterns() {
	$blocks = WP_Block_Type_Registry::get_instance();

	$maybe_unregister = [
		'core/table-of-contents' => [
			'pattern-slug-1'
			'pattern-slug-2'
		],
		'pluginslug/block-name'  => [
			'pattern-slug-3'
		]
	];

	foreach ( $maybe_unregister as $block => $patterns ) {
		if ( ! $blocks->is_registered( $block ) ) {
			foreach ( $patterns as $pattern ) {
				unregister_block_pattern( $pattern );
			}
		}
	}
}

Relevant links

Props to @ndiego and @welcher for review.

2 responses to “Snippet: Conditionally unregister patterns”

  1. Mostafa Baharloo Avatar
    Mostafa Baharloo

    Very good

  2. Teented Avatar
    Teented

    One of major stress I encountered on WordPress is unable to edit some WordPress theme. The question is how to edit WordPress starter theme

Leave a Reply

Your email address will not be published. Required fields are marked *