我用的是Google的prettify代码高亮,自带5个样式,样式也可以自己编辑有html知识即可
Google的prettify的Github地址:https://github.com/google/code-prettify
主题在头部或者底部加入prettify css和js文件,也可以通过CDN地址http://www.bootcdn.cn/prettify/ 外链加载
然后在functions.php中加入以下代码
复制代码
- //防止代码转义
- function meow_prettify_esc_html($content){
- $regex = '/(<pre\s+[^>]*?class\s*?=\s*?[",\'].*?prettyprint.*?[",\'].*?>)(.*?)(<\/pre>)/sim';
- return preg_replace_callback($regex, 'meow_prettify_esc_callback', $content);}
- function meow_prettify_esc_callback($matches){
- $tag_open = $matches[1];
- $content = $matches[2];
- $tag_close = $matches[3];
- $content = esc_html($content);
- return $tag_open . $content . $tag_close;}
- add_filter('the_content', 'meow_prettify_esc_html', 2);
- add_filter('comment_text', 'meow_prettify_esc_html', 2);
- //强制兼容
- function meow_prettify_replace($text){
- $replace = array( '<pre>' => '<pre class="prettyprint linenums" >' );
- $text = str_replace(array_keys($replace), $replace, $text);
- return $text;}
- add_filter('the_content', 'meow_prettify_replace');
然后就完事啦,编辑文章的时候就可以直接插入 <pre class="prettyprint linenums">代码</pre>
评论(10)