Google Analytics is one of the most popular website analytics tools available for WordPress. While there are several WordPress plugins that allow you to insert Google Analytics code into your website, there is no need for an additional plugin if you just want to make it work. All you have to do is using the code snippet given below and copy-pasting the Google Analytics tracking code in between.
Unlike many other code snippets, you should include the opening and closing PHP tags. They are there on purpose. Because we are adding a non-PHP script in between. The PHP tags simply switch from PHP to HTML and then again switch back to PHP.
Usage
- To add Google Analytics code without using an extra plugin that may contain a lot of unnecessary features you do not want.
- Quickly add tracking code to your website without having to spend time managing and updating the plugins.
Also note that, even though the code is created to add Google Analytics code to your website. You can add almost any script you want to add to your footer. For example, if you joined an ad network and you want to add a script to the footer, you can use the same code snippet and just replace the Google Analytics code with your custom script.
Code
// Add Google Analytics code to WordPress footer
function add_google_analytics() { ?>
// Your Google Analytics code
<?php }
add_action('wp_footer', 'add_google_analytics');
Explanation
- The comment to determine this code snippet from other codes in your files.
- Creating our function
add_google_analytics
where we are going to put our code. Also we are exiting from PHP to HTML so that we can add our HTML tags for the script. - A comment which can be replaced with your Google Analytics code that starts with the
<script>
tag and ends with another</script>
tag. - Entering the PHP mode again so that we can continue writing in PHP.
- Adding our function to the
wp_footer
hook, so that it will be added inside our WordPress footer section.