How to use the condition has_block

Support MB Blocks How to use the condition has_blockResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #33621
    marcodedomarcodedo
    Participant

    Hi I have a block like this:

    add_filter( 'rwmb_meta_boxes', function( $meta_boxes ) {
        $meta_boxes[] = [
            'title' => 'Name of block',
            'id'    => 'my-block',
            'type'  => 'block', // Important.
    
            // 'icon'  => 'awards', // Or you can set a custom SVG if you don't like Dashicons
            'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="currentColor" d="M485.5 0L576 160H474.9L405.7 0h79.8zm-128 0l69.2 160H149.3L218.5 0h139zm-267 0h79.8l-69.2 160H0L90.5 0zM0 192h100.7l123 251.7c1.5 3.1-2.7 5.9-5 3.3L0 192zm148.2 0h279.6l-137 318.2c-1 2.4-4.5 2.4-5.5 0L148.2 192zm204.1 251.7l123-251.7H576L357.3 446.9c-2.3 2.7-6.5-.1-5-3.2z"></path></svg>',
            'category' => 'layout',
            // 'context' => 'side', // The block settings will be available on the right sidebar.
            'supports' => [
                'align' => ['wide', 'full'],
            ],
    
            'render_template' => get_template_directory () . '/inc/blocks/my-block-content.php', // The PHP template that renders the block.
            'enqueue_style'   => get_template_directory_uri () . '/inc/blocks/style.css', // CSS file for the block.
    
            // Now register the block fields.
            'fields' => [
                
                [
                    'type' => 'text',
                    'id'   => 'title',
                    'name' => 'Title of Text',
                ],
            ],
        ];
        return $meta_boxes;
    } );
    

    Now, I need to check if this block was used in the post, I found the following function: https://developer.wordpress.org/reference/functions/has_block/

    if ( has_block( 'my-namespace/block-name' ) ) {
     // Do stuff here.
    }
    

    but it is not clear to me which block name I should enter

    I want to specify that the block is registered in this position: /wp-content/themes/my-theme/inc/blocks/register.php

    #33649
    marcodedomarcodedo
    Participant

    Solved thanks to this article
    https://wordpress.stackexchange.com/questions/325659/how-to-check-if-post-has-video-or-gallery-block-in-gutenberg-blocks

    if ( has_block( 'meta-box/my-block' ) ) {
       // ...
    }
    
    #33688
    Long NguyenLong Nguyen
    Moderator

    Thanks for sharing your solution.

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.