In this post I’ll explain how to define CSS classes for WordPress menu items.
Let’s say that you want to add a specific CSS class directly to a WordPress menu item link. So for example something like this:
<a class=”piwik_link” href=”http://www.domain”>menu item</a>
In WordPress there is the “CSS Classes” setting in “advanced menu properties”. Which can be enabled in the “screen options”, when editing menus. This setting however puts the CSS class outside of the link code.
In this case I needed to add a class to track clicks on an outbound link in Piwik. Because by setting up the class “piwik_link“, directly inside the “a href” line of code, clicks can be recorded as as a “goal”.
To do this, simply navigate to the appearance editor in WordPress, and add a few lines of code to your “functions.php” file, in the bottom for example:
function add_menuclass($ulclass) { return preg_replace('/<a rel="nofollow"/', '<a rel="nofollow" class="piwik_link"', $ulclass, 1); } add_filter('wp_nav_menu','add_menuclass');
In this example, all menu links that are set rel=”nofollow” will automatically append the class “piwik_link”. You may change the code to fit your needs.
Therefore automatically each:
<a rel=”nofollow” href=”http://www.domain”>menu item</a>
will be converted to:
<a class=”piwik_link” rel=”nofollow” href=”http://www.domain”>menu item</a>
To add rel attributes in wordpress, go to menu editor -> screen options -> enable “Link Relationship (XFN)” and each menu item will have a new Link Relationship (XFN) option. In this box you can enter the desired rel attributes.
Hope that helps to add classes to WordPress menu items.
Comments are welcome of course! David.
Thanks for sharing this! Worked just fine.
I have one question:
I have 2 menus (header & footer)
Is there a way to target a specific menu to insert this (header)?
Sorry, don’t know.
Stack Overflow is your friend.
Thank you.
Thanks you very much for this function. i was trying to add custom css class from Material Design Framework to anchors and this function helped me. Thank you very much.
I have created a gist https://gist.github.com/tahirtaous/e5aebe8f1001d0187ae2#file-add-custom-css-to-anchors-links-in-wordpress
That’s awesome thank you!