WordPress website statistical code deployment actual combat: the perfect combination of Baidu statistics, GA4 and Microsoft Clarity

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

作者:

Blog Monetization & Content Strategy System

【插图:Google AdSense 单日收入 2~3 美元截图】

(1) Blog Advertisement: Earnings vs User Experience

进入 WordPress 后台 → 系列 → 系列类别 → 添加新系列类别。如图1

(2) From Advertising to Service: I reconstructed the content system of the blog with a “series categories”

系列文章总计约 85 篇。如图1

(3) My Technical Blog CTA System Design: From Classification to Series, Build Precision Conversion Solutions for Sustainable Maintenance

Specification for the use of blog content structure and classification labels (V1.0)

(4) Specification for the use of blog content structure and classification labels (V1.0)

Balance of Independent Blog: How to restart advertising, how to use “semi-automatic” strategy to balance experience and technical service conversion?

(5) Balance of Independent Blog: How to restart advertising, how to use “semi-automatic” strategy to balance experience and technical service conversion?

插入代码后,保存并预览文章,即可看到生成的流程图。以下是预览效果的截图:

(6) Insert Mermaid flowchart using the Merpress plugin in WordPress

图5:兼容性测试通过

(7) Say goodbye to flashing and non-copyable: smooth migration from SyntaxHighlighter to Code Block Pro

仔细算了算,屏幕宽度超过 1680px 的活跃用户,合计占比 超过了 35%。

(8) After struggling for several days, I finally decided to change the theme

Change the theme or go to the CDN first? The trade-off and thinking of a sequence of operations

(9) Change the theme or go to the CDN first? The trade-off and thinking of a sequence of operations

Site main navigation menu optimization review | Category selection, sequence adjustment, bilingual menu synchronization full record

(10) Site main navigation menu optimization review | Category selection, sequence adjustment, bilingual menu synchronization full record

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

(11) WordPress website statistical code deployment actual combat: the perfect combination of Baidu statistics, GA4 and Microsoft Clarity

Elegantly add multiple sets of statistical code through the WPCode plugin, and solve the problem of data loss access to Google Analytics in China

📋 Backgrounds and Goals

I had a headache when adding statistical code to a WordPress site:How to deploy multiple statistical tools at the same time without affecting the performance of the website, and ensure the accuracy of the data? Especially for Chinese-speaking websites, the stability of Google Analytics (GA4) in mainland China may lead to the loss of some traffic data.
My demands are very clear: not only to use a powerful GA4 to analyze overseas traffic, but also to take care of the access experience of domestic users; at the same time, I also want to add Microsoft’s Microsoft Clarity to see how users browse the page. I thought it was a simple ‘copy-paste-save’ three-step step, but I didn’t expect to step on a lot of pits in actual operation. Today, I will share my practice process and investigation ideas, hoping to help friends who are also tossing the statistical code.

🎯 Core scheme: multi-tool collaborative statistics

Based on the geographical distribution of website visitors and the advantages of different analytical tools, I have designed the following statistical schemes:

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>提升转化率]

Reason for tool selection

Toolcore advantageApplicable scenariosdomestic stability
Baidu StatisticsDomestic access is stable, associated with Baidu searchRecord domestic traffic and accelerate Baidu’s inclusion⭐⭐⭐⭐⭐
Google Analytics 4Powerful Event Tracking and Funnel AnalysisAnalyze overseas users and measure marketing effects⭐⭐☆☆☆
Microsoft ClarityFree heat map with session recordingBehavioral analysis, user experience optimization⭐⭐⭐⭐⭐

🛠️ Deployment process and problem solving

Step 1: Add Baidu statistical code through WPCode

In order not to make the theme files messed up, I have always been accustomed to using the WPCode plugin to manage various third-party scripts. The first is to deploy the most stable Baidu statistics in China.
When creating a new code snippet in wpcode, I selected javascript fragment type, after pasting the code, set the position to site wide header(Whole site header), the device type is selected any device type(Desktop and mobile) so that all access devices are covered.

Figure 1: Add Baidu statistics code, select the JavaScript fragment, and select Site Wide Header for Location


Baidu statistical code is successfully added, the location is selected in the header to load as soon as possible
Baidu statistics is very smooth here. But when I deploy GA4 next, I was reported by WPCode as a mistake.

Step 2: Add Google Analytics 4 code (an error is reported)

I painted the gourd and painted the GA4 part to <script> The code at the beginning is pasted, and the code type is still selected as a JavaScript fragment. When the result is saved, the system directly reports an error:unexpected token <.

Figure 2: Add Google Statistics code, select JavaScript fragment, and report an error


GA4 code triggers syntax error when selecting a JS fragment
At that time, I was a little confused, but after a closer look, I realized that the code of GA4 is a complete HTML tag (including <script> And </script>), and the JavaScript fragment type requires pure JS logic, which encounters the beginning < Naturally, the syntax is wrongly parsed.

Step 3: Solve the problem of adding GA4 code

Once the cause is found, it will be resolved quickly. I changed the code type to HTML Fragment, paste the GA4 code again, this time it was successfully saved, no error was reported.

Figure 3: Add Google statistics code, select HTML fragment, no errors are reported


After re-selecting the HTML fragment, the GA4 code is successfully saved

💡 key learning point: In WPCode,Code containing HTML tags (such as statistical code) must choose HTML fragment type, and the pure JavaScript code selects the JavaScript fragment type. This is the key to avoiding the ‘unexpected token’ error.

Step 4: Install the Microsoft Clarity plugin

It stands to reason that the Clarity code can also be managed with WPCode. But considering that the main function of Clarity is session recording and heat map, the script is relatively heavy. Although wpcode can also be set in footer, I took a look at the clarity official website and found that they actually provide a special wordpress plugin.
Since there is a native plugin, the trouble of manually managing the position of the code can be saved. The plugin will automatically inject the code in the optimal way (usually at the bottom of the page), without worrying about affecting the first screen speed, and it can also be used in wp Looking directly at the overview in the background, why not do it.
So according to the official website, I chose the WordPress platform.

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


Clarity officially provided WordPress plugin installation boot
Go straight back to the background of the blog, search for ‘Microsoft Clarity’, one-click installation and enable.

Figure 5: Search plugin in the background: Microsoft Clarity, install and enable


One-click installation of background search plug-in
When enabled, there will be an additional Clarity option in the sidebar. Click to enter and follow the prompts to log in to the Microsoft account authorization.

Figure 6: Background Microsoft Clarity, log in to Microsoft


Click to log in to your Microsoft account directly in the background
After the authorization is complete, the page will be automatically linked to the project I created in the Clarity background, and the entire deployment process is extremely silky.

Figure 7: The page after Microsoft Clarity login in the background


Status panel after the plugin is successfully connected

🔍 Authentication and Testing: Network Request Analysis

The code has been deployed, which does not mean that everything will be fine. Especially GA4, whether it can send data normally under the domestic network environment, I have always had a question mark in my heart.
In order to find out the real situation, I turned off the VPN, simulated the most realistic domestic visitor environment, opened the browser’s seamless mode, and pressed f12 Call out the developer tool, cut to network Panel, prepare ‘seeing is believing’.

Google Analytics 4 request analysis

Filter in the Network panel google, refresh the page, I saw a very interesting phenomenon:

Figure 8: GoogleTagManager Response 200, Google-Analytics has been pending


GA4 request status captured by the Network panel
As shown in the screenshot, the work of GA4 is actually divided into two steps:

  1. Load Core Script: request https://www.googletagmanager.com/gtag/js?id=G-89CMTD9395, this request status code is 200 (success). Description GA4’s code base has been downloaded.
  2. Back to traditional meter data: request https://www.google-analytics.com/g/collect?...(a long list of requests containing information such as page address, title, etc.), but the status of this request has always been Pending (hanging/waiting).
    What does this mean? It means that the code is installed without a problem, but because the domestic network is google-analytics.com The interference of this data collection interface makes the data not sent out at all. In the end this page browsing (PV) is lost in the GA4 background.

Baidu statistical request analysis

Since GA4 cannot be counted in China, how is Baidu’s performance? I’m in the same network panel, and I’ve changed the filter word to baidu.

Figure 9: HM.GIF Response 200, HM.JS Response 200


The two core requests of Baidu Statistics have successfully returned 200
Similar to GA4, Baidu Statistics also has two key requests, and both are successful:

  1. https://hm.baidu.com/hm.js?...: state 200, responsible for loading the core js script of Baidu statistics.
  2. https://hm.baidu.com/hm.gif?...: state 200, which is a request that is actually used to send data. Baidu Statistics is very smart. It carries parameters by requesting a 1×1 pixel transparent GIF image. This ancient but cross-domain compatibility is excellent, and it is extremely stable under the domestic network.
    See these two 200, I know that the data of domestic visitors has been firmly recorded in the background of Baidu statistics.

contrast conclusion

The access stability of Baidu Statistics in China is much higher than that of GA4, which can reliably record the traffic data of all domestic visitors, as a cornerstone tool for domestic traffic statistics. Although GA4 is powerful, there is indeed a problem of unstable data collection in the domestic network environment.

📊 Final plan: three tools work together

Based on the test results, I determined the final solution for the three tools to work together:

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>与会话回放

The division of labor and data value of each tool

ToolMain responsibilitiesdata valueView frequency
Baidu StatisticsDomestic traffic statisticsProvide accurate domestic PV/UV data, which is associated with Baidu searchdaily view
Google Analytics 4Overseas flow analysisAnalyze international user behavior and measure the effect of overseas marketingweekly analysis
Microsoft ClarityVisualize user behaviorProvide session recording, heat map, and discover UX problemsWeekly in-depth analysis

💡 Best practices and suggestions

1. Code deployment best practices

📖 Detailed code deployment advice

  • Use the WPCode plugin: Avoid direct editing of theme files, facilitate code management and migration
  • Code type selection:
  • HTML Fragment: suitable for code containing HTML tags (such as GA4, Clarity code)
  • javascript fragment: For pure JavaScript code
  • location settings:
  • Header: Statistical code, verification code
  • footer: Clarity and other heavier scripts to avoid affecting the page load speed (if deployed through WPCode)
  • Device Type: always choose any device type, make sure all device users are covered
  • Clarity deployment: It is recommended to use the official WordPress plugin to automatically optimize the loading position

2. Network request verification method

🔧 How to verify that the statistical code is working

  1. Open Developer Tools: Press on the website page f12 Open Developer Tools
  2. Switch to the Network panel: Refresh the page, observe the network request
  3. Filter critical requests:
  • Baidu Statistics: Filter hm.gif(data report) and hm.js(script load)
  • GA4: filter group(data collection) and gtag/js(script load)
  • Clarity: filter Clarity.ms
  1. Check status code: Make sure that the key request status code is 200, without Pending or Failed status

3. Data analysis strategy

📊 How to use the data of three sets of tools effectively

  • Domestic traffic analysis: subject to Baidu statistics, focus on sources, keywords, page views
  • Overseas flow analysis: Mainly GA4, analyze user path, conversion funnel, demographic characteristics
  • Behavioral Deep Analysis: Use Clarity’s session recording and heat map to discover page design issues
  • Integration Analysis: Regularly compare the data of the three sets of tools, find the difference and optimize the statistical deployment

⚠️ Frequently Asked Questions and Solutions

❓ FAQs

Q1: Why is the data of GA4 inaccurate in China?

A1: GA4’s data collection request (Google-Analytics.com) is unstable in China and is often interfered or reset, resulting in data loss. The core script (GoogleTagManager.com) may load successfully, but the data cannot be sent.

Q2: Why is there a big difference between Baidu Statistics and GA4 data?

A2: The main reasons include: 1) GA4 failed to request in part; 2) The statistical mechanism of the two sets of tools is different; 3) The time zone and filter settings are different. It is recommended to analyze domestic traffic on the basis of Baidu statistics.

Q3: Will Microsoft Clarity affect website speed?

A3: Clarity uses asynchronous loading, which has little impact on website speed. Its script loading takes place in the background, does not block page rendering, and there is no traffic restriction for free.

Q4: How to avoid code conflicts in WPCode?

A4: 1) Each statistical tool uses independent code snippets; 2) Avoid repeated deployment of the same code; 3) Check the status of the code snippet regularly to ensure that there are no errors.

🎉 Summary and results

By deploying Baidu Statistics, Google Analytics 4 and Microsoft Clarity three sets of statistical tools, I built a complete website statistics system:

  1. Solved the problem of domestic data loss: Baidu Statistics ensures a complete record of domestic traffic data
  2. Retains overseas analytical capabilities: GA4 Continue to analyze international user behavior
  3. gained deep behavioral insights: Clarity provides session recording and heat maps to optimize user experience

💡 Final suggestion: For WordPress websites for Chinese users,Baidu Statistics + Microsoft Clarity It is a basic must-have combination, and GA4 is used as a supplement to analyze overseas traffic. All statistical codes are managed through the WPCode plug-in, which not only facilitates maintenance, but also avoids the risk of directly modifying the theme file.
Through this solution, I have not only solved the data collection problem of Google Analytics in mainland China, but also obtained comprehensive website analysis capabilities, which has laid a solid foundation for data-driven website optimization.

Site main navigation menu optimization review | Category selection, sequence adjustment, bilingual menu synchronization full record

评论

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.