1. Using a Plugin (Recommended)
Add the Google Analytics code without editing theme files by using a plugin like Insert Headers and Footers.
Steps:
- Install and activate the Insert Headers and Footers plugin.
- Navigate to Settings > Insert Headers and Footers.
- Paste the Google Analytics code in the Scripts in Header section.
- 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:
- Go to Appearance > Theme File Editor in the WordPress dashboard.
- Open the
header.php
file. - 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:
- Go to Appearance > Theme File Editor.
- Open the
functions.php
file. - 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