How to Add CSS Class Directly to The WordPress Menu Item Link

In this post I’ll explain how to define CSS classes for WordPress menu items.

WordPress Menu Item CSS

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”.

CSS Class WordPress Menu Item Link

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.

4 thoughts on “How to Add CSS Class Directly to The WordPress Menu Item Link”

  1. 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)?

    Reply

Leave a Comment