Gutenberg: has_block doesn't return true when a block is inside a reusable block

Created on 4 Nov 2019  路  2Comments  路  Source: WordPress/gutenberg

If a block is inside a reusable block, has_block doesn't return true.

Steps to reproduce the behavior:

  1. Add a block inside a reusable block. (Let's say prfx/myblock)
  2. Add action in plugins php file to wp_enqueue_scripts
    if (has_block('prfx/myblock')) {

    wp_register_script('my-script', plugins_url( 'dist/assets/myscript.min.js', dirname( __FILE__ )), array(), null, true );

    wp_enqueue_script('my-script');

    }
  1. At this point the script is not loaded to site, but the block is in the page.
  2. Add the block to the page separate/outside to reusable block
  3. Now the script loads.

Could has_block function also validate with blocks inside reusable blocks?

Desktop:

  • Windows 10
  • Firefox 70.0.1
  • Gutenberg Version 6.8.0
[Block] Block [Feature] Parsing

Most helpful comment

In the meantime, this function will do the job:

function has_reusable_block( $block_name, $id = false ){
    $id = (!$id) ? get_the_ID() : $id;
    if( $id ){
        if ( has_block( 'block', $id ) ){
            // Check reusable blocks
            $content = get_post_field( 'post_content', $id );
            $blocks = parse_blocks( $content );

            if ( ! is_array( $blocks ) || empty( $blocks ) ) {
                return false;
            }

            foreach ( $blocks as $block ) {
                if ( $block['blockName'] === 'core/block' && ! empty( $block['attrs']['ref'] ) ) {
                    if( has_block( $block_name, $block['attrs']['ref'] ) ){
                       return true;
                    }
                }
            }
        }
    }

    return false;
}

Maybe the name of the function should be sth like has_block_in_reusable instead of has_reusable_block, anyway...

All 2 comments

In the meantime, this function will do the job:

function has_reusable_block( $block_name, $id = false ){
    $id = (!$id) ? get_the_ID() : $id;
    if( $id ){
        if ( has_block( 'block', $id ) ){
            // Check reusable blocks
            $content = get_post_field( 'post_content', $id );
            $blocks = parse_blocks( $content );

            if ( ! is_array( $blocks ) || empty( $blocks ) ) {
                return false;
            }

            foreach ( $blocks as $block ) {
                if ( $block['blockName'] === 'core/block' && ! empty( $block['attrs']['ref'] ) ) {
                    if( has_block( $block_name, $block['attrs']['ref'] ) ){
                       return true;
                    }
                }
            }
        }
    }

    return false;
}

Maybe the name of the function should be sth like has_block_in_reusable instead of has_reusable_block, anyway...

Possible duplicate of #17048.

Was this page helpful?
0 / 5 - 0 ratings