Reputation: 358
I know there are many different ways you can include the Google Analytics script into a Wordpress website, but I won't use plugins for this.
So the way I would like to prefer is to code it into the theme's functions file, giving me two options left. (yes it's a child theme)
wp_enqueue_scripts
The outcome of the above ways will be different so with my little Wordpress experience, I was wondering what should be the safest and most secure way to embed it into a Wordpress site? Eventually I might consider also the difference in loading time, also the fastest way?
Upvotes: 0
Views: 1538
Reputation: 646
Google Analytics
tracking code is asynchronous. It doesn't need to wait for the code to finish loading to continue rendering elements that come after it on the page. It's a good idea to get into the habit of placing the GTM container snippet
in the head section because that's where asynchronously loading libraries should be placed.
Upvotes: 0
Reputation: 417
This code adds Analytics and excludes the traffic of connected users (useful to avoid registering your visits).
<?php
if ( !is_user_logged_in() ) {
function addAnalytics() {
$analyticsTag = "<!-- Google Analytics -->
<script> Codice di traccimento </script>
<!-- Google Analytics -->";
echo $analyticsTag;
}
add_action( 'wp_enqueue_scripts', 'addAnalytics');
}
?>
Upvotes: 2
Reputation: 1805
wp_enqueue_script
with parameter $in_footer
set to false
, is the same as hardcoding the script into the html head (in fact, it would be included in the place where wp_head()
is called, which should be inside the <head></head>
tags).
wp_enqueue_script
gives you the ability to add a dependency to the script you are adding, but for google analytics you don't need any, so from safety and security you are covered. From speed's point of view, I guess hardcoding it would be very slightly faster, but your header will look bigger, so it's up to you to trade readability and enqueue it or just add it as a script. The header usually is not a large file anyway, so most of the times I just copy-paste the code inside the head as it is.
Upvotes: 2
Reputation: 1222
If you have already created a child theme just copy over the header file and add your google analytics code before the closing tag. That is an easy option and that is what I always do for my WP sites.
Upvotes: 1