Best place to insert the Google Analytics code in wordpress site

1. Using a Plugin (Recommended)

Add the Google Analytics code without editing theme files by using a plugin like Insert Headers and Footers.

Steps:

  1. Install and activate the Insert Headers and Footers plugin.
  2. Navigate to Settings > Insert Headers and Footers.
  3. Paste the Google Analytics code in the Scripts in Header section.
  4. Click Save.

This method ensures the code remains active even after changing themes.

2. Adding Manually to Theme Files

Insert the code directly into the header.php file before the </head> tag.

Steps:

  1. Go to Appearance > Theme File Editor in the WordPress dashboard.
  2. Open the header.php file.
  3. Paste the Google Analytics code before the closing </head> tag:
  
<head>
  <!-- Other head elements -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'YOUR_TRACKING_ID');
  </script>
</head>

Note: Replace YOUR_TRACKING_ID with your actual Google Analytics tracking ID.

3. Adding via functions.php

A cleaner way is to use the functions.php file to enqueue the script.

Steps:

  1. Go to Appearance > Theme File Editor.
  2. Open the functions.php file.
  3. Add this PHP code:
  
<?php
function add_google_analytics() {
  echo '<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"></script>';
  echo '<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag("js", new Date());
    gtag("config", "YOUR_TRACKING_ID");
  </script>';
}
add_action('wp_head', 'add_google_analytics');
?>

Note: This method ensures the code is included dynamically in the <head> section.

Conclusion

For most users, using a plugin is the easiest and safest method. However, if you prefer manual control, inserting the code in the <head> section of header.php or dynamically via functions.php are excellent options.

No comments:

Post a Comment