WordPress Code Snippets插件提供了一种在网站上运行 PHP 代码片段的简单、干净和便捷的方法。有了这个插件,不再需要将自定义代码添加到主题functions.php
文件中。Code Snippets插件非常小巧,几乎不会额外消耗系统资源。
Code Snippets插件的特点
- 图形化的管理界面
- 便捷的编辑器
- 自动检查代码语法,防止语法错误
- 可设置代码执行的条件/范围,例如:任意地方、仅管理后台、仅前端、仅运行一次
- 可保存草稿
也就是说,原来需要修改主题functions.php
文件的,现在仅需要在Code Snippets插件中进行操作即可,这样的好处是即使更换了主题,自定义的代码也会得到保留,而且相比编辑functions.php
文件更方便、安全、可靠。
Code Snippets插件使用说明
Code Snippets插件自带几种自定义代码模板:
默认内容为:
add_shortcode( 'shortcode_name', function () { $out = '<p>write your HTML shortcode content here</p>'; return $out; } );
将<p>write your HTML shortcode content here</p>
替换成自己的HTML代码即可,另外shortcode_name
是短代码名称,可以自己取一个,然后在其它需要调用地方用do_shortcode掉用,示例:
<?php echo do_shortcode("[shortcode_name]"); ?>
add_action( 'wp_head', function () { ?> <style> /* write your CSS code here */ </style> <?php } );
例如添加百度统计代码:
add_action( 'wp_head', function () { ?> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?cc042cc33ef4958d8bd4d7b1917f7a65"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <?php } );
如果要将JS代码添加到尾部,则可以将wp_head
改成wp_footer
,依然以百度统计代码为例:
add_action( 'wp_footer', function () { ?> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?cc042cc33ef4958d8bd4d7b1917f7a65"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <?php } );
Order snippets by name与Order snippets by date则是代码排序的示例。
编辑好所需的代码后,记得点保存,并点击启用开关,如下图:
另外可以通过Run snippet everywhere 、Only run in administration area、Only run on site front-end、Only run once四个选项,控制代码的执行范围,这四个选项对应的是:任意地方运行、仅管理后台运行、仅前端运行、仅运行一次。
提示:但凡通过添加到主题functions.php
文件中可执行的代码,均可添加到Code Snippets插件中,和添加到functions.php的效果是一样的。