将自定义 <li> 添加到 Wordpress 导航菜单

Roo*_*Roo 1 php wordpress

我只是无法完全理解自定义步行者如何在 worpress 中工作:

主题的 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()
        )
    );
}
Run Code Online (Sandbox Code Playgroud)

沃克看起来像这样:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

覆盖的方法是行不通的。

如果我尝试覆盖另一种方法,例如:

class Last_Item_Walker extends Walker_Nav_Menu { 

    function end_el( &$output, $item, $depth = 0, $args = array() ) {
            $output .= "<br>"; // for demonstration
        $output .= "</li>\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

这个有效,添加了 br 标签,但这不是我想要的,我想在 /ul 之前自定义最后一个 li。

有人可以帮我解决这个问题吗?

Roo*_*Roo 5

好的,使用过滤器更容易。

/**
 * 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);
Run Code Online (Sandbox Code Playgroud)