WordPress 通过菜单页面显示项目的方式是使用 walker 对象。在这种情况下,该对象的特定类称为 Walker_Nav_Menu。你可以在wp-includes\nav-menu-template.php找到它。
Walker_Nav_Menu 是一个非常简单的类。您可以看到链接和菜单结构是如何在那里构建的。函数start_el 和end_el 用于构建菜单项。函数start_lvl 和end_lvl 用于嵌套菜单。在这种方法中,我们将主要使用start_el 和end_el。
在你的functions.php 创建一个类,用与父类非常相似的方法扩展Walker_Nav_Menu:
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,但这没关系,因为如果没有被覆盖,您的类将自动继承父类的方法。
然后,在您的主题文件中,您可以像这样调用 wp_nav_menu:
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 将使用您的自定义类和函数,以便您可以修改输出的代码。