在上一教程修改wp主题使得升级后也不丢失—自制子主题中我们说明了如何通过创建子主题使得修改的css不会被母模板升级时覆盖。而且我们只用到了style.css。本节我们将利用上面提到的functions.php添加Google Analytic跟踪代码。
- 首先当然是有一个google账户, 然后访问Google Analytic,注册账户并添加你的网站。注意网址应该填你的WP网址。随后得到你的跟踪代码。
- 在子主题根目录新建functions.php:
sudo vim /var/www/wordpress/wp-content/themes/twentyfifteen_child/functions.php
, 其内容为:<?php // Include the Google Analytics Tracking Code (ga.js) function google_analytics_tracking_code(){ $propertyID = 'UA-62235536-1'; // GA Property ID ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '<?php echo $propertyID; ?>', 'auto'); ga('send', 'pageview'); </script> <?php } // include GA tracking code before the closing head tag //add_action('wp_head', 'google_analytics_tracking_code'); // OR include GA tracking code before the closing body tag add_action('wp_footer', 'google_analytics_tracking_code'); ?>
这里你需要修改的只有一处, $GAID你应该填第1步中跟踪代码里面的形如UA-xxxxxxxx-x.
- 这里我们是把代码加到页脚处, 你也可以加到页眉处,代码里已经说清楚了如何改变。页脚的好处是加快页面的载入速度, 但跟踪只在页面完全载入时才行。页眉正好反过来了。
- 作为练习, 你可以添加google站长工具验证代码到wp_head中。而且在google analytic后台将其关联。
- 最后google analytic一般要等一段时间才能检测到数据, 按照上述方法添加成功后, 你可能需要等待几小时才能看到统计信息。
本作品采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载本站内容必须也遵循署名-非商业用途-保持一致的创作共用协议.