Using WordPress ‘has_blocks()’ PHP function

The has_blocks() WordPress PHP function determines 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.

Usage

if (has_blocks($post)) {
    // Do something
}

Parameters

  • $post int|string|WP_Post|null (optional) – Post content, post ID, or post object. Defaults to the global $post. Default: null.

More information

See WordPress Developer Resources: has_blocks()

Examples

Check if a Post has Blocks

This example checks if the current post has blocks and performs some action if it does.

if (has_blocks()) {
    // Do something
}

Custom Block Parser

This example demonstrates how to use has_blocks() to check if the content has any blocks before using a custom block parser.

class WPDocs_Custom_Block_Parse {
    function parse() {
        // Do something
    }
}

function wpdocs_custom_block_parser() {
    return 'WPDocs_Custom_Block_Parse';
}

$post_content = get_the_content();

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');
}

Check if a Specific Post has Blocks

This example checks if a specific post with a given ID has blocks.

$post_id = 42;

if (has_blocks($post_id)) {
    // Do something
}

Check if a Post Object has Blocks

This example checks if a WP_Post object has blocks.

$post_object = get_post(42);

if (has_blocks($post_object)) {
    // Do something
}

Check if a Content String has Blocks

This example checks if a given content string has blocks.

$content_string = "Some content with <!-- wp:paragraph -->a block<!-- /wp:paragraph -->";

if (has_blocks($content_string)) {
    // Do something
}