I build a navigation within a wordpress blog. the items are displayed like this:
The icon is applied by using the bootstrap classes glyhicon-glyphiconname
. I add the classes dynamically. The php code for that:
function add_specific_menu_location_atts( $atts, $item, $args ) {
// check if the item is in the primary menu
if( $args->theme_location == 'directentries' ) {
foreach($item as $key => $value) {
if($key == 'title') {
$catIcon = setCatIcon($value);
}
}
// add the desired attributes:
$atts['class'] = 'btn btn-primary btn-lg glyphicon glyphicon-'.$catIcon;
}
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_specific_menu_location_atts', 10, 3 );
$args = array(
'theme_location' => 'directentries',
'depth' => 1,
'container' => false,
'menu_class' => 'nav',
'link_before' => '<br>',
//'link_before' => 'span class"glyphicon"',
'walker' => ''
);
wp_nav_menu($args);
The problem here is, that the font of the link text is (of course) glyhicon, otherwise the icon would not apply to the link. So: The correct way would be to apply a span using the link-before parameter when initialising the menu. But I need to apply my dynamic classname to the span then. I think I could access the link_before param within my filter class using the $args parameter..
The current markup is this:
And I need it to be linke this:
Does anyone have an idea how to apply a span and vary the classes?
.
Although a custom Nav Walker class might be a good (better?) solution as @Trix suggested, I want to answer the question how to apply a span using my filter. This code did it:
function add_specific_menu_location_atts( $atts, $item, $args ) {
if( $args->theme_location == 'directentries' ) {
foreach($item as $key => $value) {
if($key == 'title') {
$catIcon = setCatIcon($value);
}
}
foreach($args as $key => $value) {
if($key == 'link_before') {
$args->$key = '<span class="glyphicon glyphicon-'.$catIcon.'"></span><br>';
}
}
// add the desired attributes:
$atts['class'] = 'btn btn-primary btn-lg';
}
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_specific_menu_location_atts', 10, 3 );