I’m trying to add a CSS hover effect to my theme’s main menu and the effect is based on an attribute passed in a <span>
element. The problem is that I am unable to produce this dynamically with the title of each menu item. Here is the HTML that I would like to produce:
<nav>
<a href="#"><span data-hover="Home">Home</span></a>
<a href="#"><span data-hover="About">About</span></a>
<a href="#"><span data-hover="Contact">Contact</span></a>
</nav>
Now in WP I tried adding the link_before
and link_after
attribute in order to add the <span>
element but I’m not sure how to produce the title for each menu item for the “data-hover” attribute. Any help would be highly appreciated.
When calling the
wp_nav_menu()
function you can pass the<span>
tags in thelink_before
ylink_after
arguments:To have differents attributes in the span for each menu item you may need to use a custom nav_walker. For example, the next custom Nav_Walker is the default from WordPress, I’ve just modified it to add the
<span>
with thedata-hover
attribute:The custom nav walker, in this case
Custom_Walker
must be in functions.php or included in it:Or maybe better (or not, I’m not sure because it needs a query foreach menu item via the
get_post()
function if we want to run the filter only for the title of menus and not to all post titles), usethe_title
filter hook (see toscho answer for a better way to usethe_title
filter hook if you decide to use this filter instead the custom nav-walker):You can filter the nav menu itemâs title with
the_title
.Unfortunately, this filter is used on many other places too, so you have to turn on the filter as late as possible, and you should turn it off when the items have been parsed.
Sample, code, not tested: