问题描述
我熟悉 WordPress 并使用 WordPress 菜单系统.但我正在寻找一种将自定义 HTML 添加到 wp_nav_menu()
的方法.
I'm familiar with WordPress and using the WordPress menu system. But I'm looking for a way to add custom HTML to wp_nav_menu()
.
我正在尝试创建这样的菜单:
I'm trying to create a menu like this:
请注意产品下的下拉菜单如何包含图像和链接.我想重新创建这个.我看过一些插件,但更愿意编写代码.
Notice how the drop down menu under products contains an image and a link. I'd like to re-create this. I've looked at a few plugins, but would rather code it.
我不介意对图片和链接进行硬编码,但我希望保持使用 WordPress 管理菜单的灵活性.
I don't mind hard coding the image and link, but I'd like to keep the flexibility of using WordPress to manage the menus.
推荐答案
WordPress 通过菜单页面显示项目的方式是使用 walker 对象.在这种情况下,此对象的特定类称为 Walker_Nav_Menu.您可以在 wp-includes\nav-menu-template.php
中找到它.
The way WordPress goes through the menu pages to display the items, is using a walker object. In this case the specific class for this object is called Walker_Nav_Menu. You can find it in wp-includes\nav-menu-template.php
.
Walker_Nav_Menu
是一个非常简单的类.您可以看到链接和菜单结构是如何在那里构建的.函数 start_el
和 end_el
用于构建菜单项.函数 start_lvl
和 end_lvl
用于嵌套菜单.在这种方法中,我们将主要使用 start_el
和 end_el
.
The Walker_Nav_Menu
is a pretty simple class. You are able to see, how the links and the menu structure are built there. The functions start_el
and end_el
are used to build the menu-items. Functions start_lvl
and end_lvl
are for nesting menus. In this approach we'll be mainly using start_el
and end_el
.
在您的 functions.php
中创建一个类,使用与父类非常相似的方法扩展 Walker_Nav_Menu
:
In your functions.php
create a class, to extend Walker_Nav_Menu
with pretty similar methods to the parent class:
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_el ( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
// Copy all the start_el code from source, and modify
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
// Copy all the end_el code from source, and modify
}
}
在这些函数中,$item
是您的菜单项,如果您愿意,您可以使用它根据当前菜单项查询其他内容.请注意,我没有包含 start_lvl
和 end_lvl
,但这并不重要,因为您的类将自动继承父类方法,如果没有被覆盖.
In those functions, the $item
is your menu-item, with which you can query additional contents according to the current menu-item, if you want to. Note that I didn't include start_lvl
and end_lvl
, but that doesn't matter, since your class will automatically inherit the parent classes methods, if not overwritten.
然后,在您的主题文件中,您可以像这样调用 wp_nav_menu:
Then, in your theme files, you can call wp_nav_menu like this:
wp_nav_menu(array(
'theme_location' => 'main',
'container' => false,
'menu_id' => 'nav',
'depth' => 1,
// This one is the important part:
'walker' => new Custom_Walker_Nav_Menu
));
WordPress 将使用您自定义的类和函数,以便您可以修改输出的代码.
WordPress will use your custom class and functions, so that you can modify what code is output.
这篇关于如何将自定义 HTML 添加到 wp_nav_menu?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!