Google Analytics for WordPress

To set up Google Analytics tracking for WordPress you don’t need any third-party plugin. It can be easily done using a child theme. A child theme, is a code that modifies the current theme in a way that won’t interfere with future upgrades. To enable Google Analytics, start by creating a child theme using the official documentation.

Now, you need to get you Google Analytics tracking code. Over the years the tracking code had a few different versions. You should make sure you are getting the latest tracking code, which currently looks like:

<br />
&lt;!-- Global site tag (gtag.js) - Google Analytics --&gt;<br />
&lt;script async src=&quot;https://www.googletagmanager.com/gtag/js?id=UA-380837-9&quot;&gt;&lt;/script&gt;<br />
&lt;script&gt;<br />
  window.dataLayer = window.dataLayer || [];<br />
  function gtag(){dataLayer.push(arguments);}<br />
  gtag('js', new Date());</p>
<p>  gtag('config', 'UA-380837-9');<br />
&lt;/script&gt;<br />

To get the tracking code, follow the instructions on this page.

Now we add the tracking code to each page using the child theme. In your child theme’s directory, edit the functions.php file and add the following lines. Replace the tracking code with the one you acquired.

<br />
// Add Google Analytics tracking<br />
function my_google_analytics_header() {<br />
?&gt;<br />
&lt;!-- Global site tag (gtag.js) - Google Analytics --&gt;<br />
&lt;script async src=&quot;https://www.googletagmanager.com/gtag/js?id=UA-380837-9&quot;&gt;&lt;/script&gt;<br />
&lt;script&gt;<br />
  window.dataLayer = window.dataLayer || [];<br />
  function gtag(){dataLayer.push(arguments);}<br />
  gtag('js', new Date());</p>
<p>  gtag('config', 'UA-380837-9');<br />
&lt;/script&gt;<br />
&lt;?php<br />
}<br />
add_action( 'wp_head', 'my_google_analytics_header');<br />

This adds the tracking code to the <head> of every page.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.