admin管理员组

文章数量:1289753

We often use has_block to enqueue scripts only if a certain block is present. With something like vimeo you used to be able to write has_block('core-embed/vimeo').

What is the proper way now to enqueue scripts for JUST the vimeo variation, not all core/embed 's?

We often use has_block to enqueue scripts only if a certain block is present. With something like vimeo you used to be able to write has_block('core-embed/vimeo').

What is the proper way now to enqueue scripts for JUST the vimeo variation, not all core/embed 's?

Share Improve this question asked Jul 28, 2021 at 14:18 Marin CarrollMarin Carroll 333 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

We can try to use has_block(), has_blocks() and parse_blocks() to find an embed with a given providerNameSlug attribute.

Untested suggestion:

function has_block_embed_by_provider_wpse( $provider, $post = null ) {
    if ( ! has_blocks( $post ) ) {
        return false;
    }
 
    if ( ! is_string( $post ) ) {
        $wp_post = get_post( $post );
        if ( $wp_post instanceof WP_Post ) {
            $post = $wp_post->post_content;
        }
    }
   
    if ( has_block ( 'embed', $post ) ) {
        $blocks = parse_blocks ( $post );
        foreach( (array) $blocks as $block ) {
            if ( isset( $block['attrs']['providerNameSlug'] ) 
                 && $provider === $block['attrs']['providerNameSlug'] 
            ) {
                return true;
            }
        }
    }
    return false;
}

Usage Examples:

has_block_embed_by_provider_wpse( 'vimeo' )

has_block_embed_by_provider_wpse( 'vimeo', $content )

has_block_embed_by_provider_wpse( 'vimeo', $post )

has_block_embed_by_provider_wpse( 'vimeo', 123 )

has_block_embed_by_provider_wpse( 'vimeo', get_post( 123 ) )

本文标签: wp enqueue scriptHow to target block variations with hasblock()