来自 Shortcode 的木材菜单

Timber Menu from Shortcode

是否可以在像 [my_menu slug="1"].

这样的短代码中获取菜单项

下面是我根据 YouTube shortcode in the docs

尝试的
<?php
// Called from within an init action hook in functions.php
add_shortcode( 'my_menu', 'my_menu_shortcode' );

function my_menu_shortcode( $atts ) {
    
    if( isset( $atts['slug'] ) ) {
        $slug = sanitize_text_field( $atts['slug'] );
        
        $args = array('depth' => 2,);
        $menu = new Timber\Menu( $slug , $args);           
    
    }else{
        $menu = 'Please Enter a Menu Slug';
    }

   
    return Timber::compile( 'shortcodes/my_menu.twig', array( 'menu' => $menu ) );
}
// my_menu.twig
{% if menu %}

    {{menu}}

   <nav>
    <ul class="nav-main">
        {% for item in menu.items %}
           <a class="nav-main-link" href="{{ item.link }}">{{ item.title }}</a>
        {% endfor %}
    </ul>
</nav>
    

{% endif %}

当我应该使用 menu.get_items 时,我有 menu.items

以下作品

<?php
// Called from within an init action hook in functions.php
add_shortcode( 'my_menu', 'my_menu_shortcode' );

function my_menu_shortcode( $atts ) {
    
    if( isset( $atts['slug'] ) ) {
        $slug = sanitize_text_field( $atts['slug'] );
        
        $args = array('depth' => 2,);
        $menu = new Timber\Menu( $slug , $args);           
    
    }else{
        $menu = 'Please Enter a Menu Slug';
    }
      
   
    return Timber::compile( 'shortcodes/mey_menu.twig', array( 'menu' => $menu ) );
}

和树枝文件


{% if menu %}
   <nav>
        <ul class="nav-main">
          {% for item in menu.get_items %}
                <a href="{{ item.link }}">{{ item.title }}</a>
            {% endfor %}
        </ul>
    </nav>
{% endif %}