微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

简码中的木材菜单

如何解决简码中的木材菜单

是否可以在 [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.items 时,我使用了 menu.get_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 %}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。