Search code examples
wordpresswordpress-gutenbergwordpress-block-theme

Add shortcode to Navigation block


I am using a FSE theme and I need to add a short code in the navigation block. I Know there is no direct way to do that but i also have found this hook block_core_navigation_render_inner_blocks. Using that hook works if i try to add the mini-cart (WooCommerce) block but now i need to add a shortcode. The code is:

add_filter(
    'block_core_navigation_render_inner_blocks',
    function( $inner_blocks ) { 

        $menu_item = [
            'blockName'    => 'core/shortcode',         
            'attrs'        => [
                "text" => 'fk_cart_menu',               
            ],
            'innerBlocks'  => [],
            'innerHTML'    => '',
            'innerContent' => [],
        ];
        $inner_blocks->offsetSet( null, $menu_item );
        return $inner_blocks;
    }
);

I do not see the shortcode in the navigation block. Why? The shortcode exists, i also checked it with shortcode_exists() that returns true I also tried using [fk_car_menu] with parentesis, without any luck.


Solution

  • Despite the name, the shortcode block doesn't actually return a block; so the shortcode block cannot be rendered by block_core_navigation_render_inner_blocks as it only renders blocks. This is why in your test, the WooCommerce block worked but the shortcode block did not.

    A possible way around this limitation is to register your own dynamic block that calls do_shortcode(...) in the render callback then use it in your add_filter(...) code, eg:

    function so78080575_render_callback() {
      // return your shortcode, not echo..
      return do_shortcode( '[fk_cart_menu]' );
    }
    
    /* Register a simple, dynamic block */
    function so78080575_register_block() {
      if ( !function_exists( 'register_block_type' ) ) {
        // return if block editor unavailable
        return;
      }
      register_block_type( 'so/78080575',
        $args = array(
          'title' => 'FK Cart Menu',
          'icon' => 'smiley',
          'render_callback' => 'so78080575_render_callback' // to render shortcode
        )
      );
    }
    add_action( 'init', 'so78080575_register_block' );
    
    
    add_filter(
        'block_core_navigation_render_inner_blocks', // accepts only valid blocks
        function( $inner_blocks ) { 
    
            $menu_item = new WP_Block(['blockName' => 'so/78080575']);
            $inner_blocks->offsetSet( null, $menu_item );
    
            return $inner_blocks;
        }
    );
    

    Hopefully this gets you closer to what you are looking to achieve...