You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress特定城市页面加载对应Google Analytics脚本问题求助

Fixing Per-City Google Analytics Tracking in WordPress

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.
  • elseif is more efficient than separate if statements (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:

  1. Add a custom field like google_analytics_id to each city page.
  2. Fetch it in your header.php with:
    $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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:28:56