在WordPress中,wp_nav_menu
函数用于显示导航菜单。如果你想要在菜单项中添加子菜单,并且希望在这些子菜单项前添加一个<i>
标签(通常用于图标),你可以通过自定义菜单 Walker 来实现。
以下是一个简单的示例,展示如何创建一个自定义的 Walker 类来在子菜单项前添加<i>
标签:
class Custom_Menu_Walker extends Walker_Nav_Menu {
function start_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"sub-menu\">\n";
}
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array)$item->classes;
$classes[] = 'menu-item-' . $item->ID;
$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 . '>';
$atts = array();
$atts['title'] = !empty($item->attr_title) ? $item->attr_title : '';
$atts['target'] = !empty($item->target) ? $item->target : '';
$atts['rel'] = !empty($item->xfn) ? $item->xfn : '';
$atts['href'] = !empty($item->url) ? $item->url : '';
// 添加 <i> 标签到子菜单项
if ($depth > 0) {
$atts['class'] = 'menu-item-icon';
}
$atts = apply_filters('nav_menu_link_attributes', $atts, $item, $args, $depth);
$attributes = '';
foreach ($atts as $attr => $value) {
if (!empty($value)) {
$value = ( 'href' === $attr ) ? esc_url($value) : esc_attr($value);
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
// 在子菜单项前添加 <i> 标签
if ($depth > 0) {
$item_output = '<i class="your-icon-class"></i>' . $item_output;
}
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
}
然后,在你的主题的functions.php
文件中,注册这个自定义的 Walker:
function custom_nav_menu($args = array()) {
$args['walker'] = new Custom_Menu_Walker();
wp_nav_menu($args);
}
最后,在你的模板文件中调用这个函数来显示菜单:
custom_nav_menu(array(
'theme_location' => 'primary',
'menu_class' => 'nav-menu'
));
在这个示例中,your-icon-class
是你想要添加的图标的 CSS 类名。你需要确保在你的样式表中有相应的图标样式定义。
这种方法的优势在于它提供了灵活性,允许你自定义菜单的输出,而不需要修改 WordPress 的核心文件。你可以根据需要添加任何 HTML 或 CSS 类,以便更好地控制菜单的外观和行为。
应用场景包括但不限于:
如果你遇到了问题,比如图标没有显示,可能的原因包括:
your-icon-class
没有在你的样式表中正确定义。解决方法:
functions.php
文件中,并且没有语法错误。通过这种方式,你可以轻松地在 WordPress 的导航菜单中添加带有图标的子菜单项。
领取专属 10元无门槛券
手把手带您无忧上云