Create a Custom WordPress Function to Install Google Analytics

Installation of Google Analytic 


A better way, if you have the know how is to create a custom function to install the Analytics code. There is usually a Theme Functions (functions.php) file that comes with a theme. It depends on the theme developer whether this file suffers the same issues as the Header (or other) file when updating. A lot of the time this is set aside for custom functions by the user (us) and not be overwritten during a theme update. You can’t count on that however. I won’t cover it here but creating your own custom plugin might be better.

Here’s how to add a function to install the GA code to WordPress:

1. Go to Appearance >> Editor.

2. Under Templates on the right side, locate and click on the Theme Functions (functions.php) file.

3. Add the code below to the file.

Now, there may be a placeholder for custom functions, there may not. If there are existing functions, it is safe to assume this file will be overwritten when an upgrade occurs. Just keep a backup of your functions and make it a habit to manually add them back in after a theme update. It’s easier to manually update a functions file than any other, since there is specific placement usually for the other files.

If there are no php tags you will need to add them. I won’t cover that here. If there is existing code in there, there will be existing php tags. Near the bottom of the file you should see a ? then the “greater than” symbol. Include your function just before that spot.

Finally, the code:

add_action('wp_footer', 'custom_ga1');

function custom_ga1() {

In the above code, I created a function called “custom_ga1″ for lack of a better name. It’s important that function name is unique from WordPress functions, and functions of other themes and other plugins. If you replace the name be sure to replace it in both spots. I like to use the site name that I am working on as the prefix, and a meaningful name for the suffix. You can leave it as is and feel safe because there is very little chance of it causing any conflicts.

Of course, replace REPLACE-WITH-GA-CODE with your actual Google Analytics code. It’s important the code is wrapped in double quotes as is shown. This code with place the GA code in the footer of the site.