[英]Adding custom <li> to Wordpress navigation menu
I just cant fully understand how custom walkers work in worpress: 我只是无法完全了解自定义步行者在worpress中的工作方式:
Code in theme's home.php (actually all code is included from other file to not mess HTML) looks like this: 主题的home.php中的代码(实际上所有代码都包含在其他文件中,不会弄乱HTML)看起来像这样:
/**
* Contains wordpress function with array with parameters
* @return string HTML output
*/
function show_main_navigation() {
return wp_nav_menu(
array(
'theme_location' => 'header-menu',
'echo' => false,
'depth' => '-1',
'walker' => new Last_Item_Walker()
)
);
}
Walker looks like this: 沃克看起来像这样:
class Last_Item_Walker extends Walker_Nav_Menu {
function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= '<li class="spec"><a href="#" title="title">title</a></li>'; // my custom <li>
$output .= "$indent</ul>\n";
}
}
Overwritten method just does not work. 覆盖的方法就是行不通的。
If I try to overwrite another method, for example: 如果我尝试覆盖另一种方法,例如:
class Last_Item_Walker extends Walker_Nav_Menu {
function end_el( &$output, $item, $depth = 0, $args = array() ) {
$output .= "<br>"; // for demonstration
$output .= "</li>\n";
}
}
This one works, adds br tag but this is not what i want, i want to customize last li before /ul. 这是可行的,添加了br标签,但这不是我想要的,我想在/ ul之前自定义最后一个li。
Can somebody help me with this? 有人可以帮我吗?
Ok it was easier to do with filters. 好的,使用过滤器更容易。
/**
* Hardcodes shop item in navigation
* @param string $items HTML with navigation items
* @param object $args navigation menu arguments
* @return string all navigation items HTML
*/
function new_nav_menu_items($items, $args) {
if($args->theme_location == 'header-menu'){
$shop_item = '<li class="spec"><a href="#" title="title">title</a></li>';
$items = $items . $shop_item;
}
return $items;
}
add_filter('wp_nav_menu_items', 'new_nav_menu_items', 10, 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.