简体   繁体   中英

Including Google Analytics wordpress

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)

  • creating a function with analytics script inside, linking this to header/footer
  • using the default way Wordpress asks to enqueue scripts at 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?

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.

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');
   }
?>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM