我对编码不是很在行,但我在谷歌上搜索了很多,编辑了一些脚本,效果很好,但我无法实现我所需要的。
代码如下:
class description_walker extends Walker_Nav_Menu
{
function start_el(&$output, $item, $depth = 0, $args = Array(), $id = 0)
{
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\\t", $depth ) : \'\';
$class_names = $value = \'\';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( \' \', apply_filters( \'nav_menu_css_class\', array_filter( $classes ), $item ) );
$class_names = \' class="\'. esc_attr( $class_names ) . \'"\';
$output .= $indent . \'<li id="menu-item-\'. $item->ID . \'"\' . $value . $class_names .\'>\';
$attributes = ! empty( $item->attr_title ) ? \' title="\' . esc_attr( $item->attr_title ) .\'"\' : \'\';
$attributes .= ! empty( $item->target ) ? \' target="\' . esc_attr( $item->target ) .\'"\' : \'\';
$attributes .= ! empty( $item->xfn ) ? \' rel="\' . esc_attr( $item->xfn ) .\'"\' : \'\';
$attributes .= ! empty( $item->url ) ? \' href="\' . esc_attr( $item->url ) .\'"\' : \'\';
$prepend = \'<strong>\';
$append = \'</strong>\';
$description = ! empty( $item->description ) ? \'<span>\'.esc_attr( $item->description ).\'</span>\' : \'\';
if($depth != 0)
{
$description = $append = $prepend = "";
}
$item_output = $args->before;
$item_output .= \'<a\'. $attributes .\'>\';
$item_output .= $args->link_before .$prepend.apply_filters( \'the_title\', $item->title, $item->ID ).$append;
$item_output .= $description.$args->link_after;
$item_output .= \'</a>\';
$item_output .= $args->after;
$output .= apply_filters( \'walker_nav_menu_start_el\', $item_output, $item, $depth, $args, $id );
}
}
在我的。php文件:
<?php
wp_nav_menu( array(
\'container_class\' => \'top-nav\',
\'menu_class\' => \'nav\',
\'echo\' => true,
\'before\' => \'\',
\'after\' => \'\',
\'link_before\' => \'\',
\'link_after\' => \'\',
\'depth\' => 0,
\'theme_location\' => \'topnav\',
\'walker\' => new description_walker())
);
?>
问题是我不知道如何为容器添加数据(
div
) 以及
ul
标签
例如,我得到的是:
<div class="top-nav">
<ul class="nav" ...>
<li ...></li>
</ul>
</div>
我想要这样的东西:
<div class="top-nav" mine="something">
<ul class="nav" ... mine2="something2">
<li ...></li>
</ul>
</div>
请帮帮我
最合适的回答,由SO网友:Howdy_McGee 整理而成
好吧,如果只是简单地增加一个data
属性或类似的东西,您可以使用items_wrap
参数View wp_nav_menu()
in Resources:
$items_wrap = \'<div class="top-nav" mine="something">\';
$items_wrap .= \'<ul id="%1$s" mine="something2" class="nav %2$s">%3$s</ul>\';
$items_wrap .= \'</div>\';
wp_nav_menu( array(
\'container\' => false,
\'echo\' => true,
\'before\' => \'\',
\'after\' => \'\',
\'link_before\' => \'\',
\'link_after\' => \'\',
\'depth\' => 0,
\'theme_location\' => \'topnav\',
\'items_wrap\' => $items_wrap, // The Default is: \'<ul id="%1$s" class="%2$s">%3$s</ul>\'
\'walker\' => new description_walker()
) );
这是一种更直接的前进方式,而不是与步行者或类似的东西混在一起。