I will show you how I inserted Google Analytics tracking code to this web site today.
I chose to write a WordPress plugin to accomplish this task but since I only manage 2 WordPress sites, I didn’t develop it with a lot of bells and whistles.
gid-wp-google-analytics.php
Using my favourite text/PHP editor, I created a PHP file: gid-wp-google-analytics.php. This is how it looks:
<?php /* Plugin Name: GID WP Google Analytics Plugin URI: https://www.gidblog.com/wordpress-plugin-google-analytics/ Description: Inserts Google Analytics tracking code to web pages, in the header. Author: J de Silva Version: 1.0 */ // Replace "NNNNN-N" with your Google Analytics site tracking ID define( "GID_GAID", "NNNNN-N" ); function gid_google_analytics() { // <!-- Global site tag (gtag.js) - Google Analytics --> ?> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-<?php echo GID_GAID; ?>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-<?php echo GID_GAID; ?>'); </script> <?php } add_action( 'wp_head', 'gid_google_analytics', 10 );
Do not forget to paste your own Google Analytics tracking code ID in the PHP code before uploading the file. See line no. 12 above.
Upload gid-wp-google-analytics.php
Save the file and upload it to the /wp-content/plugins/
folder of your WordPress site. On my Linux laptop, with the scp
command, this is as simple as:
scp -v $HOME/gid-wp-google-analytics.php [email protected]:/var/www/html/wp-content/plugins/
Finally, go to the Plugins page inside your WordPress site’s admin dashboard to activate this plugin.