Get the link title attribute and send it google analytics as custom label via google tag manager using beehive pro for WordPress
On the WordPress site, I have beehive pro installed, (this question is beyond the support scope) and I'm trying to get all the hyperlink's title attributes and send them to Google analytics as a custom label Google tag manager. The client has 200+ hyperlinks to PDF documents and needs to track the downloads of these files.
This piece of code dynamically applies the title attribute to each link by extracting it from the filename of the PDF file:
jQuery( function () {
function download_links() {
jQuery( 'a' ).each( function () {
var text = jQuery( this ).text();
var title = jQuery( this ).attr( 'title' );
if ( '-1' !== text.toLowerCase().indexOf( 'download' ) 'undefined' === typeof title ) {
var href = jQuery( this ).attr( 'href' );
if ( href ) {
var filename = href.split( '/' ).pop();
jQuery( this ).attr( 'title', filename );
}
}
} );
}
download_links();
jQuery( window ).bind( 'grid:items:added', function () {
download_links();
} );
The second piece of code is where I seem to be stuck as it needs to send the title from the above code as the event label in gtag, but it doesn't work. I don't know why that is?
jQuery( 'a' ).on( 'click', function () {
if ( jQuery( this ).hasAttribute( 'title' ); ) {
var title = jQuery( this ).attr( 'title' );
beehive_ga('event', 'my event', {
'event_category' : 'download',
'event_label' : title
});
}
} );
} );
All of the above code is in the functions.php file in a doc ready function that runs the script in the page footer.
Topic google-analytics jquery plugins Wordpress javascript
Category Web