I found examples adding a class to top level items, so we can display an arrow in menu items with sub-items, but is seems terrible to cope with the already built in WordPress classes, can’t display the arrow with current and css hover, it just ruins all states.
The current nav menu is like this <li><a>Text</a></li>
Is there someway to add a <span class="arrow"></span>
within the parent <a></a>
tags instead?
Example,
Add ⇒ <span class="arrow"></span>
inside ⇒ <a/></a>
tags
Thus ⇒ <li><a>Text<span class="arrow"></span></a></li>
that is parent.
The current code Adds the <span></span>
tags outside the <a></a>
tags that is parent
class My_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl(&$output, $depth, $args) {
$indent = str_repeat("t", $depth);
if('primary' == $args->theme_location && $depth ==0){
$output .='<span class="arrow"></span>';
}
$output .= "n$indent<ul class="sub-menu">n";
}
}
Original question title edited from: “add span class inside <a>
“
Have you tried using the
before
orlink_before
parameters in your array arguments when declaring yourwp_nav_menu
function?Note: use
after
orlink_after
for the opposite effect.Example,
From the Codex:
or…
Supporting resources:
http://codex.wordpress.org/Function_Reference/wp_nav_menu
This actually creates two instances where it displays a span class within the tag on the primary and secondary levels so you can add different images to your span class for designing and navigating purposes.
This helps for users and developers to show if there is a drop-down to your header menu and also makes it easier to navigate within your website.
1. Add this code below to your functions.php first.
2. Add code below to your header.php where your wp_nav_menu is installed.
Explained below is the code so it installs the new custom menu in this case would be Nav_Walker_Nav_Menu.
3. Add some CSS
So it is able to show your new span arrow images within your tags in primary and secondary level.
hope this help! 🙂
Both answer posted by userabuser and wordpress_designer are great, but I would like to post an answer what is a combination of the two.
With this answer you can use logic to define where you don’t want the
link_before
to be applied. As well as what you want to put before the link text.First create a very simple class like the one below. This class is actually only responsible for checking whenever the element is not a sub menu (
$depth <= 0
) and for cleaning and remembering thelink_before
value.The second thing you will have to do is apply the
walker
argument and thelink_before
argument to yourwp_nav_menu
array, like this: