问题描述
是否可以在 [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 %}