Function and usage of has_block() in wordpress

Question

Answers ( 1 )

    0
    2024-01-08T15:58:28+00:00

    The has_block() function in WordPress is a useful tool for theme and plugin developers, providing a way to check if a specific block type exists within a post or a piece of content. Here's a detailed explanation of this function:

    Function Signature

    has_block( string $block_name, int|string|WP_Post|null $post = null ): bool
    

    Purpose

    The has_block() function determines whether a post or a string contains a specific block type.

    Description

    • This function is designed to optimize for performance rather than strict accuracy.
    • It checks if the specified block type exists in the given post content, but it does not validate the block's structure.
    • It also does not check for synced patterns (formerly known as reusable blocks).
    • For more accurate and thorough block analysis, it is recommended to use the block parser on the post content. See parse_blocks() for more details.

    Parameters

    1. $block_name (string, required): The full block type to look for. This should be the registered name of the block, like 'core/paragraph' for a paragraph block.
    2. $post (int | string | WP_Post | null, optional): The content to check for the block. This can be either the post content, the post ID, or the post object itself. If not provided, the function will use the global $post by default. Default value is null.

    Return Value

    • bool: Returns true if the post content contains the specified block, otherwise false.

    Sample Usage

    Here's an example of how has_block() can be used in a WordPress theme or plugin:

    if ( has_block( 'core/image', get_the_ID() ) ) {
        echo 'This post contains an image block.';
    } else {
        echo 'This post does not contain an image block.';
    }
    

    In this example, has_block() checks if the current post (identified by get_the_ID()) contains an image block (core/image). Depending on the presence of the image block, it outputs a corresponding message.

    Remember, has_block() is a quick way to check for the presence of a block but not its validity or precise structure. For detailed block analysis, use parse_blocks().

Leave an answer