There are many plugin solutions on offer to add your Google Analytics tracking code to WordPress. If you’d like a lightweight option you can use the plugin Code Snippets. Once activated, go to SnippetsAdd New, name your new function as you’d like, Google Analytics for example and then insert the following function into the Code area:
function my_custom_google_analytics_tracking() { ?> <script async src="https://www.googletagmanager.com/gtag/js?id='UA-00000000-1'"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-00000000-1'); </script> <?php } add_action( 'wp_head', 'my_custom_google_analytics_tracking' );
Replace the entire example tracking code with your own tracking code.
my_custom
namespace can be replaced with your site's own namespace. For example, if this snippet was for Puro Themes we might namespace the function puro_themes
in which case the function name would become puro_themes_google_analytics_tracking
. If you replace my_custom
with your own namespace, don't forget to change the namespace in both the function name and the action at the end of the function.
In Code Snippets, set the function to Only run on site front-end, finally, Save Changes and Activate.
The above function can also be used in a child theme functions.php
file or a custom plugin.