has_blocks()
Defines whether the specified string or content of the specified post contains Gutenberg blocks.
Determines the presence of a block by the construction <!-- wp: in the passed content.
For optimization purposes, this function only determines the presence of blocks but does not check their structure. For high accuracy, use the block parser: parse_blocks().
Use has_block() to check if the specified block exists in the string.
Used By: has_block()
1 time — 0.000001 sec (speed of light) | 50000 times — 0.04 sec (speed of light) | PHP 7.2.5, WP 5.0
No Hooks.
Returns
true|false. true - has block(s), false - does not have.
Usage
has_blocks( $post );
- $post(integer/string/WP_Post/null)
- ID or post object in the content of which to check for the presence of blocks. Or you can simply pass a string (content).
Default: global $post
Examples
#1 Check the string whether there are any blocks
$content = '
<!-- wp:paragraph -->
<p>This is the content of regular posts. Thank you for your attention! </p>
<!-- /wp:paragraph -->
';
if ( has_blocks( $content ) ) {
echo 'Content has blocks'; // Display this line
}
else {
echo 'Content has no blocks;
} #2 Convert (parse) block output
-
We can use this function to pass a flag to indicate if the content has blocks when we have decoupled environment, where WP is the backend and the frontend is implemented in some other programming language.
- We can convert (parse) block output as per our requirement and pass it in the API. While, converting it can be useful to check if the content has any block. This will let us pass content efficiently by implementing parsing when it is necessary.
class WPDocs_Custom_Block_Parse {
function parse() {
// Do something
}
}
function wpdocs_custom_block_parser() {
return 'WPDocs_Custom_Block_Parse';
}
/**
* In the implementation check if content has block
*/
if ( has_blocks( $post_content ) ) {
add_filter( 'block_parser_class', 'wpdocs_custom_block_parser' );
$response_content = parse_blocks( $content );
remove_filter( 'block_parser_class', 'wpdocs_custom_block_parser' );
}
Notes
- See: parse_blocks()
Changelog
| Since 5.0.0 | Introduced. |
has_blocks() has blocks code WP 7.0
function has_blocks( $post = null ) {
if ( ! is_string( $post ) ) {
$wp_post = get_post( $post );
if ( ! $wp_post instanceof WP_Post ) {
return false;
}
$post = $wp_post->post_content;
}
return str_contains( (string) $post, '<!-- wp:' );
}