我正在尝试向所有菜单项添加数据属性,但它根本不起作用。我正在使用wp_nav_menu
也给我的菜单查询员打电话。
function menu_anchor_attributes ( $atts, $item, $args ) {
$atts[\'data-menuanchor\'] = $item->attr_title;
return $atts;
}
add_filter( \'nav_menu_link_attributes\', \'menu_anchor_attributes\', 10, 3 );
我使用JointsWP作为我的框架,其中包括以下walker:
// The Top Menu
function joints_top_nav() {
wp_nav_menu(array(
\'container\' => false, // Remove nav container
\'menu_class\' => \'horizontal menu\', // Adding custom nav class
\'items_wrap\' => \'<ul id="%1$s" class="%2$s" data-responsive-menu="accordion medium-dropdown">%3$s</ul>\',
\'theme_location\' => \'main-nav\', // Where it\'s located in the theme
\'depth\' => 5, // Limit the depth of the nav
\'fallback_cb\' => false, // Fallback function (see below)
\'walker\' => new Topbar_Menu_Walker()
));
}
// Big thanks to Brett Mason (https://github.com/brettsmason) for the awesome walker
class Topbar_Menu_Walker extends Walker_Nav_Menu {
function start_lvl(&$output, $depth = 0, $args = Array() ) {
$indent = str_repeat("\\t", $depth);
$output .= "\\n$indent<ul class=\\"menu\\">\\n";
}
}
SO网友:Howdy_McGee
每当属性为空时,WordPress过滤器决定不显示该属性,因此简单的测试如下:
function menu_anchor_attributes ( $atts, $item, $args ) {
$atts[\'data-menuanchor\'] = ( ! empty( $item->attr_title ) ) ? $item->attr_title : \'test\';
return $atts;
}
add_filter( \'nav_menu_link_attributes\', \'menu_anchor_attributes\', 10, 3 );
这样,如果标题属性尚未填充到后端,它仍将显示值为的属性
test
.