There are lots of plugin available to add Google Analytics code (or Google Tag manager code) in your WordPress. But is this really necessary to add yet another plugin, just to add a little code block (yes Google Analytics/Tag Manager code is just a little tiny code block)? We can actually avoid using a plugin with a few lines of code. wp_head
action hook is at our rescue.
function careless_google_analytics() { ?>
//your analytics/tag manager code goes here
<?php }
add_action( 'wp_head', 'careless_google_analytics' );
Above code will put your analytics code inside the <head>
section of your entire website. But some people might want not to track WP admin pages. Following code will do that trick.
function careless_google_analytics() {
if ( !is_admin ) { ?>
//your analytics/tag manager code goes here
<?php }
}
add_action( 'wp_head', 'careless_google_analytics' );
In fact, you can add any other scripts, that you need to insert in your website header using the above code.
If you need to add some script in the footer, you can do so by:
function careless_footer_script() { ?>
//your scripts/code goes here
<?php }
add_action( 'wp_footer', 'careless_footer_script' );
Code goes in the functions.php
file of your active theme.