【发布时间】: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