没有不值得去解决的问题,也没有不值得去学习的技术!

Deploying Analytics on WordPress: A Practical Guide to Baidu Tongji, GA4, and Microsoft Clarity

图8:googletagmanager 响应 200,google-analytics 一直 pending

作者:

在

Elegantly adding multiple sets of analytics code using the WPCode plugin, and resolving the data loss issue when accessing Google Analytics from within China

📋 Background and Goals

When adding analytics code to a WordPress website, I ran into a frustrating challenge: how to deploy multiple analytics tools simultaneously without compromising site performance, while ensuring data accuracy? Particularly for websites targeting Chinese users, the access stability issues of Google Analytics (GA4) in mainland China can lead to the loss of some traffic data.
My requirements were clear: I needed the powerful GA4 to analyze overseas traffic while accommodating the access experience of domestic users; I also wanted to add Microsoft Clarity to see exactly how users browse pages. I originally thought it would be a simple three-step process of “copy, paste, and save,” but I unexpectedly ran into quite a few pitfalls in practice. Today, I am sharing my implementation process and troubleshooting approach, hoping it helps others who are also struggling with analytics code.

🎯 Core Strategy: Multi-Tool Collaborative Analytics

Based on the geographic distribution of website visitors and the strengths of different analytics tools, I designed the following analytics strategy:

Mermaid
flowchart LR
    A[网站访客] --> B{访问地域判断}
    B -- 中国大陆用户 --> C[百度统计<br>稳定记录基础流量数据]
    B -- 海外用户 --> D[Google Analytics 4<br>分析国际用户行为]
    C --> E[Microsoft Clarity<br>录制会话与生成热力图]
    D --> E
    E --> F[数据整合分析]
    F --> G[优化网站体验<br>提升转化率]

Reasons for Tool Selection

ToolCore StrengthUse CaseDomestic Stability
Baidu AnalyticsStable access in China, integrated with Baidu SearchTracking domestic traffic, accelerating Baidu indexing⭐⭐⭐⭐⭐
Google Analytics 4Powerful event tracking and funnel analysisAnalyzing overseas users, measuring marketing effectiveness⭐⭐☆☆☆
Microsoft ClarityFree heatmaps and session recordingsBehavioral analysis, UX optimization⭐⭐⭐⭐⭐

🛠️ Deployment Process and Problem Solving

Step 1: Add Baidu Analytics Code via WPCode

To keep theme files from becoming cluttered, I always prefer using the WPCode plugin to manage various third-party scripts. First, I deployed Baidu Analytics, which has the most stable access in China.
When creating a new code snippet in WPCode, I selected the JavaScript Snippet type. After pasting the code, I set the location to Site Wide Header, and for the device type, I chose Any device type (desktop and mobile) to ensure coverage across all accessing devices.

Figure 1: Adding Baidu Analytics code, selecting Javascript Snippet, and setting Location to Site Wide Header


Baidu Analytics code added successfully; placed in the Header for early loading
Things went very smoothly with Baidu Analytics. However, when I deployed GA4 next, WPCode threw an error.

Step 2: Add Google Analytics 4 Code (Encountering an Error)

I followed the same pattern, pasting the GA4 code that starts with <script>, and again selected the JavaScript Snippet code type. When I tried to save, the system threw an error directly: Unexpected token <.

Figure 2: Adding Google Analytics code, selecting Javascript Snippet, resulting in an error


Selecting the JS snippet type for the GA4 code triggered a syntax error
I was a bit confused at first, but after looking closely, I realized: the GA4 code is a complete HTML tag (containing <script> and </script>), while the JavaScript Snippet type requires pure JS logic inside. Encountering the opening < naturally caused a syntax parsing error.

Step 3: Resolve the GA4 Code Addition Issue

Once I identified the cause, the fix was quick. I changed the code type to HTML Snippet, pasted the GA4 code again, and this time it saved successfully without any errors.

Figure 3: Adding Google Analytics code, selecting HTML Snippet, no error


After switching to the HTML Snippet type, the GA4 code saved successfully

💡 Key Takeaway: In WPCode, code containing HTML tags (like analytics code) must be assigned the HTML Snippet type, while pure JavaScript code should use the JavaScript Snippet type. This is the key to avoiding the “Unexpected token” error.

Step 4: Install the Microsoft Clarity Plugin

Technically, Clarity’s code could also be managed using WPCode. However, considering that Clarity’s main features are session recording and heatmaps, its script is relatively heavy. Although WPCode can also place it in the Footer, I checked the Clarity official website and found that they actually offer a dedicated WordPress plugin.
Since there is a native plugin, it eliminates the hassle of manually managing code placement. The plugin automatically injects the code optimally (usually asynchronously at the bottom of the page), so there is no need to worry about affecting above-the-fold loading speed. Plus, you can view the overview directly in the WP dashboard, which is a great bonus.
So, following the official website’s guide, I selected the WordPress platform.

Figure 4: Microsoft Clarity, installation method, selecting the WordPress platform


Clarity’s official WordPress plugin installation guide
I went straight back to the blog dashboard, searched for “Microsoft Clarity,” and installed and activated it with one click.

Figure 5: Searching for the plugin in the dashboard: Microsoft Clarity, installing and activating it


One-click plugin installation via dashboard search
Once activated, a Clarity option appears in the sidebar. Clicking it and following the prompts, I logged in to authorize with my Microsoft account.

Figure 6: Dashboard Microsoft Clarity, logging in to Microsoft


Logging into the Microsoft account directly from the dashboard
After authorization, the page automatically linked to the project I had created in the Clarity dashboard. The entire deployment process was incredibly smooth.

Figure 7: Dashboard page after logging into Microsoft Clarity


Status panel after the plugin connects successfully

🔍 Verification and Testing: Network Request Analysis

Deploying the code doesn’t mean everything is done. Especially for GA4, I still had a question mark over whether it could send data normally in a domestic network environment.
To figure out the actual situation, I turned off my VPN to simulate the most realistic domestic visitor environment, opened the browser’s incognito mode, pressed F12 to bring up the Developer Tools, switched to the Network panel, and prepared to see the truth for myself.

Google Analytics 4 Request Analysis

Filtering by google in the Network panel and refreshing the page, I observed a very interesting phenomenon:

Figure 8: googletagmanager responds 200, google-analytics remains pending


GA4 request status captured in the Network panel
As shown in the screenshot, GA4’s operation actually consists of two steps:

  1. Loading the core script: Requests https://www.googletagmanager.com/gtag/js?id=G-89CMTD9395, and this request returns a status code of 200 (Success). This indicates that the GA4 code library was downloaded successfully.
  2. Reporting analytics data: Requests https://www.google-analytics.com/g/collect?... (a long request containing information like the page address and title), but this request’s status remains Pending.
    What does this mean? It means there is no issue with the code installation, but due to domestic network interference with the google-analytics.com data collection endpoint, the data simply cannot be sent out. Ultimately, this page view (PV) is lost in the GA4 backend.

Baidu Analytics Request Analysis

Since GA4 is unreliable in China, how does Baidu Analytics perform? In the same Network panel, I changed the filter keyword to baidu.

Figure 9: hm.gif responds 200, hm.js responds 200


Both core requests for Baidu Analytics successfully return 200
Similar to GA4, Baidu Analytics also has two key requests, and both succeeded:

  1. https://hm.baidu.com/hm.js?...: Status 200, responsible for loading Baidu Analytics’ core JS script.
  2. https://hm.baidu.com/hm.gif?...: Status 200, this is the request that actually sends the data. Baidu Analytics is clever; it carries parameters by requesting a 1×1 pixel transparent GIF image. This old-fashioned method, which has excellent cross-domain compatibility, is exceptionally robust on domestic networks.
    Seeing these two 200 responses, I knew the data of domestic visitors had been securely recorded in the Baidu Analytics backend.

Comparative Conclusion

Baidu Analytics’ access stability in China is far higher than that of GA4. It can reliably record all domestic visitor traffic data, serving as the foundational tool for domestic traffic analytics. GA4, while powerful, does indeed suffer from unstable data collection issues in domestic network environments.

📊 Final Strategy: Three Tools Working Together

Based on the test results, I finalized the collaborative strategy using the three tools:

Mermaid
timeline
    title 网站统计体系工作流程
    section 用户访问网站
        加载统计代码 : 百度统计<br>核心脚本加载
        : GA4<br>核心脚本加载
        : Clarity<br>核心脚本加载
    section 数据收集阶段
        百度统计 : 通过 hm.gif<br>发送PV数据 (国内稳定)
        : GA4 尝试通过 collect<br>发送数据 (国内可能失败)
        : Clarity 后台录制<br>用户会话
    section 数据整合分析
        百度统计后台 : 查看国内流量<br>基础数据
        GA4 后台 : 查看海外流量<br>与转化分析
        Clarity 后台 : 查看热力图<br>与会话回放

Division of Labor and Data Value for Each Tool

ToolMain ResponsibilityData ValueReview Frequency
Baidu AnalyticsDomestic traffic analyticsProvides accurate domestic PV/UV data, integrated with Baidu SearchDaily
Google Analytics 4Overseas traffic analysisAnalyzes international user behavior, measures overseas marketing effectivenessWeekly
Microsoft ClarityUser behavior visualizationProvides session recordings and heatmaps to identify UX issuesWeekly in-depth analysis

💡 Best Practices and Recommendations

1. Code Deployment Best Practices

📖 Detailed code deployment recommendations

  • Use the WPCode plugin: Avoid directly editing theme files, facilitating easier code management and migration
  • Code type selection:
  • HTML Snippet: Suitable for code containing HTML tags (e.g., GA4, Clarity code)
  • JavaScript Snippet: Suitable for pure JavaScript code
  • Location settings:
  • Header: Analytics code, verification code
  • Footer: Heavier scripts like Clarity, to prevent impacting page load speed (if deployed via WPCode)
  • Device type: Always select Any device type to ensure coverage for all device users
  • Clarity deployment: It is recommended to use the official WordPress plugin, which automatically optimizes the loading position

2. Network Request Verification Method

🔧 How to verify if the analytics code is working properly

  1. Open Developer Tools: Press F12 on the website page to open Developer Tools
  2. Switch to the Network panel: Refresh the page and observe the network requests
  3. Filter key requests:
  • Baidu Analytics: Filter hm.gif (data reporting) and hm.js (script loading)
  • GA4: Filter collect (data collection) and gtag/js (script loading)
  • Clarity: Filter clarity.ms
  1. Check status codes: Ensure the key request status codes are 200, with no pending or failed statuses

3. Data Analysis Strategy

📊 How to effectively utilize data from the three tools

  • Domestic traffic analysis: Rely on Baidu Analytics, focusing on traffic sources, keywords, and page views
  • Overseas traffic analysis: Primarily use GA4 to analyze user paths, conversion funnels, and audience demographics
  • In-depth behavior analysis: Use Clarity’s session recordings and heatmaps to discover page design issues
  • Integrated analysis: Regularly compare data from the three tools to identify discrepancies and optimize the analytics deployment

⚠️ Common Issues and Solutions

❓ Frequently Asked Questions

Q1: Why is GA4 data inaccurate in China?

A1: GA4’s data collection requests (google-analytics.com) are unstable for access within China, frequently experiencing interference or resets, which leads to data loss. The core script (googletagmanager.com) might load successfully, but the data cannot be sent.

Q2: Why is there a large discrepancy between Baidu Analytics and GA4 data?

A2: The main reasons include: 1) GA4 experiences partial request failures in China; 2) The two tools have different tracking mechanisms; 3) Differences in time zones and filter settings. It is recommended to rely on Baidu Analytics for analyzing domestic traffic.

Q3: Will Microsoft Clarity affect website speed?

A3: Clarity uses asynchronous loading, which has minimal impact on website speed. Its script loads in the background without blocking page rendering, and it is free with no traffic limits.

Q4: How can I avoid code conflicts in WPCode?

A4: 1) Use an independent code snippet for each analytics tool; 2) Avoid duplicate deployments of the same code; 3) Regularly check the status of code snippets to ensure there are no errors.

🎉 Summary and Results

By deploying Baidu Analytics, Google Analytics 4, and Microsoft Clarity, I built a comprehensive website analytics system:

  1. Resolved the domestic data loss issue: Baidu Analytics ensures that domestic traffic data is fully recorded
  2. Retained overseas analysis capabilities: GA4 continues to analyze international user behavior
  3. Obtained in-depth behavioral insights: Clarity provides session recordings and heatmaps to optimize user experience

💡 Final Recommendation: For WordPress websites targeting Chinese users, Baidu Analytics + Microsoft Clarity is an essential base combination, with GA4 serving as a supplement for analyzing overseas traffic. Managing all analytics code centrally through the WPCode plugin makes maintenance easy and avoids the risks of directly modifying theme files.
Through this strategy, I resolved Google Analytics’ data collection issues in mainland China while gaining comprehensive website analytics capabilities, laying a solid foundation for data-driven website optimization.

系列导航

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系