Add CSS Class Directly to WordPress Menu Item Link

In some cases you might want to add a CSS class directly to a WordPress menu item link. For example:

<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);

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.

Caring is sharing.. thank you! -David

Twitter Button Facebook Button Google Button LinkedIn Button

Write a Comment


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