WordPress特定城市页面加载对应Google Analytics脚本问题求助
Hey Diego, let's get this sorted out for you! The issue you're seeing isn't just a cache problem—your current PHP code has a syntax mistake that's causing the wrong GA ID to load every time. Let's break down the solutions step by step.
First: Fix the PHP Logic (The Root Cause)
Your if statements don't use curly braces {}, so only the line immediately after each if is conditional. The $city_id_google assignments are running unconditionally every time, which means they're overriding each other regardless of the current page.
Here's the corrected PHP code structure:
<?php // Initialize variables first to avoid undefined errors $img_src = ''; $city_id_google = ''; if(is_page('city_1')) { $img_src = 'city_1_image.jpg'; $city_id_google = 'UA-97242948-24'; } elseif(is_page('city_2')) { $img_src = 'city_2_image.jpg'; $city_id_google = 'UA-97242948-7'; } // Add more elseif blocks for other cities here ?> <!DOCTYPE html> <html> <head> ... <?php if(!empty($city_id_google)) : ?> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $city_id_google ?>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '<?php echo $city_id_google ?>'); </script> <?php endif; ?> </head>
- Using
{}ensures both the image source and GA ID are only set when the page matches. elseifis more efficient than separateifstatements (it stops checking once a match is found).- Wrapping the GA script in
if(!empty($city_id_google))prevents loading the script on non-city pages.
Handling WordPress Caching
If you're using a caching plugin (like WP Rocket, W3 Total Cache) or server-level caching, it will serve cached versions of your pages. After updating your PHP code:
- Clear your WordPress cache plugin's cache.
- Test in incognito mode (or clear your browser cache) to avoid loading old cached content.
- If you have server-side caching (e.g., Cloudflare, NGINX cache), clear that too.
Would a JS Implementation Be Better?
JS can work well if you want to bypass server caching entirely, since it runs client-side. Here's a reliable JS approach that checks the current page URL to load the correct GA ID:
// Place this in your theme's footer.php or use wp_enqueue_script to add it properly <script> // Map city slugs to their corresponding GA IDs const cityGaMap = { 'city_1': 'UA-97242948-24', 'city_2': 'UA-97242948-7' // Add more city-slug: GA-ID pairs here }; // Extract the current page slug from the URL const currentSlug = window.location.pathname.split('/').filter(part => part).pop(); const targetGaId = cityGaMap[currentSlug]; if(targetGaId) { // Dynamically load the gtag script const gtagScript = document.createElement('script'); gtagScript.async = true; gtagScript.src = `https://www.googletagmanager.com/gtag/js?id=${targetGaId}`; document.head.appendChild(gtagScript); // Initialize Google Analytics window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', targetGaId); } </script>
This method evaluates the page URL every time a user loads the page, so it avoids cache-related mismatches entirely.
Final Pro Tip
For better scalability (instead of hardcoding every city), use custom fields for each city page:
- Add a custom field like
google_analytics_idto each city page. - Fetch it in your
header.phpwith:$city_id_google = get_post_meta(get_the_ID(), 'google_analytics_id', true);
This way you don't have to edit header.php every time you add a new city.
内容的提问来源于stack exchange,提问作者Diego Cespedes

