inserting google 'onclick' tracking link attribute in wordpress - wordpress

I am looking for a way to modify the links on my Wordpress site so it tracks all my 3rd party links.
I was able to find some help with the, how to create the correct tracking code in Google Analytics, but the second part of the process is to add some specific link attributes.
Here is the example which they suggest I replicate:
<'a href="www.blog-hosting-service.com/myBlog" onclick="_gaq.push(['_link', 'www.blog-hosting-service.com/myBlog']); return false;">View My Blog
Does anyone know where I can insert this code link attributes so I can collect the external clicks via Google Analytics?

JQuery would be the best way in my opinion.
// start by getting the current page path (the one you are sending to tracker)
var pathname = window.location.pathname;
// ready handler to change the links on hosts not equal to location host
$(document).ready(function() {
$('a[href^="http://"]').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
_gaq.push(['_link', pathname]);
});
});

Related

Google Global Site Tag: how to override page referrer

I set up Google Global Site Tag for an Angular SPA. I'd like to override the page referrer that is passed to Google.
Use case: after logging in (using oAuth2), the user is redirected to the app. At this point, the url contains sensitive auth data (auth code). This url then gets logged to Google Analytics, which of course should be avoided.
I use the Angulartics2 lib with the GST provider, which internally uses the following code to send page track events to Google (according to Google's documentation on SPA route tracking):
gtag('config', trackingId, params);
By including the following line, I'm able to override the referrer (dr) in the query parameters:
params.page_referrer = 'https://my-custom-referrer.com';
index.html:
<script async src="https://www.googletagmanager.com/gtag/js"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
</script>
Code for tracking the page view event:
gtag('config', 'G-XXXXXXXXXX', {
page_location: 'http://localhost:4200',
page_path: '',
page_referrer: 'https://my-custom-referrer.com',
});
This leads to the following request being sent to google (note the dr properties, which hold the referrer):
As you can see:
The query string uses the correct referrer
However, the request payload still contains the original referrer containing sensitive data
I've tried setting the page referrer with the following line of code:
gtag('set', { page_referrer: 'https://my-custom-referrer.com' });
but this results in the same behaviour.
How can I make sure the request body also uses the overridden referrer? There used to be a setting within the Analytics dashboard to exclude certain referrers, but in the new version (Google Analytics for properties) it has disappeared.
Have you checked out the referral exclusion list?
Generally, if it redirects off your domain for authentication, you don't really want to count it as a referral, because then it will replace the true acquisition data for your users. You want to exclude it so the session is kept intact.
Also, you stated that you're using google tag manager (GTM), but your code and links to the documentation are for gtag.js, which is NOT GTM.
To set the referrer field in GTM, you need to locate the GA tag OR GA Settings tag and under the "fields to set" area, set the referrer field to your liking. Like so:
Though careful that if you override this for everything there could be issues with data accuracy, so you want to conditionally override this based on where it is coming from.
Not a solution, but a workaround. It pushes the current page (without paths or query parameters) to the history, which is then used by Google as the page referrer. At least it allows you to keep sensitive information out of Google Analytics.
history.pushState({ page: 1 }, '', window.location.origin);

How to add a separate Analytics for each website page in Wordpress

We have a WordPress installation that has locations as separate pages.
For example: mysite.com/colorado and mysite.com/alabama
We need separate google analytics for each of these as well as 1 for all of mysite.com.
Is there a way to do this with a WordPress plugin(s) or will we need to hand code some things?
Thanks in advance!
If I'm not mistaken, Google Analytics lets you view your analytics in a breakdown like that. That said, if you do need individual scripts, it would be relatively easy to program in. There may be some plugins that do this, but I'm not aware of any in particular, though a cursory glance showed plugins like Header and Footer Scripts that allow you to add scripts on a page by page basis.
Some themes also allow you to add SEO/Script settings per page/post. If that's the case, you can just open up each page and dump each script tag in the "header scripts" or similar section, and call it good. (Genesis is an example of a theme that does this).
If not, programming this would be relatively straight forward. I'd do it something like this:
add_action( 'wp_head', 'display_analytics_by_page', 1 );
function display_analytics_by_page(){
// Default Script Code with individual UA codes replaced
$script = '<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=[UA-CODE]"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(\'js\', new Date());
gtag(\'config\', \'[UA-CODE]\');
</script>';
// Array of UA codes by state
$codes = array(
'Alabama' => 'UA-123456789-1',
'Oregon' => 'UA-987654542-3',
'Vermont' => 'UA-000000000-0'
);
// Get title of this page
$title = get_the_title();
// If this page title exists in the codes array, swap placeholder and echo it.
if( isset($codes[$title]) ){
echo str_replace( '[UA-CODE]', $codes[$title], $script );
}
}
I commented along the way, but the gist is to put in the "default" script, but pull out the UA code. This will only work if you need the same exact script code in each one, otherwise you'll have to add each script to the $codes array instead.
Then create an array of the UA Codes (or full scripts if needed), keyed by the page title.
Then check the page title, and if that exists, pull that code in and echo it. This is run on the wp_head hook, so you just need to put this code in your functions.php (or similar) file.
If you want to go easy with no-coding, then go with a plugin. Jump to Plugins > Add New and Search for Google Analytics in the search box. Install the plugin named Google Analytics for WordPress (Formerly GADWP). Activate and connect the plugin with your Google Analytics property. When all is done, you will see a new tab beside your post's title. See a screenshot here.
And if you want the net analytics for the whole web site then head to your admin dashboard. A new widget will appear there with the analytics.
Documentation for the plugin can be found here.
I hope it helps.
I'm curious why you need a separate GA account for all the locations? Common practice in this scenario would be:
Use 1 account
Create 1 GA view for the entire domain
Create +1 view for each location by filtering traffic based on the URL
If the different accounts are related to limiting user access, know that you can grant user access based on each property view.

How to track Outbound links without breaking links to affiliate templates with no GA code

I have hundreds of affiliate templates and when I change the GA file, it applies to all the templates.
If I want to track outbound links, I have no choice but to put the GA javascript code in all my templates, as well as the outbound links.
Javascript is this:
<script>
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
My understanding is that the outbound link (like below) will break if the GA tracking code is not included on a template (i.e. UA-#######-#) :
Track this link
Some of the affiliates do not have or want their GA code (i.e. UA-#######-#) included in the template.
Is there a way to set up outbound tracking without breaking the links on templates without GA code?
Thank you.
Yes, you can create a Measurement Protocol hit to send the data without using GA code.
The Google Analytics Measurement Protocol allows developers to make HTTP requests to send raw user interaction data directly to Google Analytics servers
The hit looks something like this
www.google-analytics.com/collect?v=1&tid=UA-XXXXX-Y&cid=555&t=pageview&dp=%2Fhome
Where tid =Tracking ID / Property ID.
Learn more about the measurement protocol here: https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide

How to send traidtional GA event in GTM's custom HTML tag

I'm using GTM in my company's online shop, and I installed some other tag via GTM's custom HTML tag, like this:
<script>
//some JS code...
var customParam=[{"key":"value"}];
var jsElm=document.createElement("script");
jsElm.type="text/javascript";
jsElm.async=true;
jsElm.src="https://some_tags.com/tag.js?s=CV";
document.body.appendChild(jsElm);
if(today < some date)
{
SEND GA EVENT here.....
}
</script>
The traditional GA event script
ga('send', 'event', 'XXX', 'pageview', 'some description', 1);
isn't working anymore here.
How do I did this ?
And I heard someone said that I should put data into DataLayer and do some bla bla bla... but I was understanding that too few to try. Is that a right way ?
I am going to answer with another question. Why are you sending events through HTML tags instead of Google Analytics Tag that are build just for that purpose?
I ll work with the assumption that you are new with this tool but the idea is that GTM replaces all old GA code on site.
Just create a new Tag and select 'Universal Analytics' and after that you can choose which kind of information you want on Google Analytics.
Its pretty self explanatory as a tool so i strongly recommend you to forget about those old GA codes and work with what you got.
In addition to this have in mind that you can use custom javascript variables to scrap DOM values in case you need to.
Here is our guru Simo Ahava: https://www.simoahava.com/
If you need anything else just ask.

How do I add custom dimensions to Google Analytics with React Router?

My current analytics setup looks like this:
this.context.router.listen(location => {
analytics.page(location.pathname, {
title: document.title,
url: `${config.HOST_URL}${this.context.router.createHref(location)}`,
path: this.context.router.createHref(location),
referrer: document.referrer,
state: location.state,
});
});
The amount of data in the location object is pretty minimal. The question is, how do I get information about an item that is loaded in a componentDidMount block into the page tracking?
In this particular instance, I am trying to add information about an artwork that a user is looking at into Google analytics as a custom dimension. The link below shows how it would normally be added.
https://support.google.com/analytics/answer/2709828?hl=en#example-hit
I'm using react-router v2
From the information given, I'd say your best bet is on the pages you want to add more data put a condition in the listener to NOT log if loading that page. Then in the componentDidMount where you have the data call the analytics for the page.
Basically just override it for those pages that need more data.

Resources