0

Can anybody tell me how I can add a "data-track" tag to the links in my menu. When I go to the dashboard -> menus, I can add any custom HTML.

I would like it to go from this:

<a href="http://www.detailingwiki.org/articles/">Article index</a>

to this:

<a data-track="navigation|click|article-index" href="http://www.detailingwiki.org/articles/">Article index</a>

The first part of the code can always be the same (i.e. "data-track="navigation|click") the part at the end should copy the text from the link. In the example above that is "article-index", but it should just take whatever the text for the link is. (not sure if spaces are allowed....)

I haven't been able to do it myself, and I don't want to edit the core wordpress files.

0

So there's actually a filter for this, provided your theme doesn't use its own menu walker class:

function add_data_track_attribute( $atts, $item, $args ) {
    $title = apply_filters( 'the_title', $item->title, $item->ID );
    // $title = sanitize_title($title); // if you need a slug-like title
    $atts['data-track'] = 'navigation|click|'.$title;
    return $atts;
}
add_filter('nav_menu_link_attributes', 'add_data_track_attribute', 10, 3);

Note the commented-out line: I'm not sure what the data-track attribute does and, as you say, it might not allow spaces. If it doesn't, that line will transform the title into a slug, which should be acceptable for this.

Hope this helps!

| improve this answer | |
  • Thanks MacPrawn, I'm gonna try it out now. The Data-track code creates an event in Analytics. Adding this to the code of a link makes it easier to follow it in Analytics and to see how many times the link is clicked. – Vincent van Rooij Feb 2 '17 at 21:00
  • Awesome! Your code does exactly what I wanted. If you look at the code for the links in the menu to the left, you'll see the "data-track" part :D detailingwiki.org/articles Thank you. Next hurdle is to see if I can also add it to the links in the right sidebar. (actually, I want to do this with each and every link) – Vincent van Rooij Feb 2 '17 at 21:03
0

If anybody is looking for this same solution, but with the correct Google Analytics Event Tracking code, see below:

function add_data_track_attribute( $atts, $item, $args ) {
    $title = apply_filters( 'the_title', $item->title, $item->ID );
    $title = sanitize_title($title); // if you need a slug-like title
    $atts['onClick'] = 'ga(\'send\', \'event\', \'navlink\', \'click\', \''.$title.'\');';
    return $atts;
}
add_filter('nav_menu_link_attributes', 'add_data_track_attribute', 10, 3);

The part you want to change is in the end: navlink - change this to the category your event falls into. In my case it mean "link inside the navigation"

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.