【问题标题】:Timber Menu from Shortcode简码中的木材菜单
【发布时间】:2021-06-29 22:45:31
【问题描述】:

是否可以像 [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 %}

【问题讨论】:

  • Timber 版本 1。输出我使用 [my_menu slug="1"] 但这会破坏网站。

标签: php wordpress twig shortcode timber


【解决方案1】:

当我应该使用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 %}

【讨论】:

    猜你喜欢
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2017-10-09
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多