The has_block() WordPress PHP function determines if a post or a string contains a specific block type.
Usage
Here’s a simple example of how to use this function:
if ( has_block( 'core/gallery' ) ) { echo 'This post contains a gallery block.'; } else { echo 'This post does not contain a gallery block.'; }
In this case, if the post contains a ‘core/gallery’ block, the function will return true
, and the message ‘This post contains a gallery block.’ will be displayed. Otherwise, it will return false
, and ‘This post does not contain a gallery block.’ will be displayed.
Parameters
- $block_name (string): The full block type you are looking for. For example, ‘core/gallery’.
- $post (_int|string|WPPost|null): The post content, post ID, or post object. This is optional and defaults to the global $post variable. If not provided, the function uses the content of the current post.
More information
See WordPress Developer Resources: has_block()
This function does not work in reusable blocks. If you need to check blocks within a reusable block, you need to parse content first. It also does not support arrays, so if you need to check for multiple blocks, use ||
(or) operator between your checks.
Examples
Checking if a post contains a specific block
if ( has_block( 'core/paragraph' ) ) { echo 'This post contains a paragraph block.'; }
This will display ‘This post contains a paragraph block.’ if the post has a ‘core/paragraph’ block.
Checking a specific post for a block
if ( has_block( 'core/paragraph', 42 ) ) { echo 'Post 42 contains a paragraph block.'; }
This will check if post 42 contains a ‘core/paragraph’ block.
Checking for multiple blocks
if ( has_block( 'core/paragraph' ) || has_block( 'core/gallery' ) ) { echo 'This post contains either a paragraph or a gallery block.'; }
This will check if the post contains either a ‘core/paragraph’ block or a ‘core/gallery’ block.
Checking for a custom block
if ( has_block( 'my-namespace/my-custom-block' ) ) { echo 'This post contains my custom block.'; }
This checks if the post contains a custom block defined as ‘my-namespace/my-custom-block’.
Checking a string for a block
$content = '...'; // Some string content if ( has_block( 'core/paragraph', $content ) ) { echo 'The provided content contains a paragraph block.'; }
This checks the provided string $content
for a ‘core/paragraph’ block.