has_blocks()
Determine whether a post or content string has blocks.
This test optimizes for performance rather than strict accuracy, detecting the pattern of a block but not validating its structure. For strict accuracy, you should use the block parser on post content.
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.
Return
true|false
. Whether the post has blocks.
Usage
has_blocks( $post );
- $post(int|string|WP_Post|null)
- Post content, post ID, or post object.
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 6.4.3
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:' ); }