boxmoe_header_banner_img

Hello! 欢迎来到盒子萌!

加载中

文章导读

wordpress文章内容评论内容防代码转义不用插件代码高亮专用


avatar
专收爆米花 2019年4月4日 5.23k

我用的是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)

查看评论列表
评论头像
junxi chen 2019年06月20日
能说明下具体的用法么?下载的最新版的主题没有高亮显示哦。。
评论头像
专收爆米花 博主 2019年06月20日
主题设置里的,文章,开启代码高亮
评论头像
chanhey 2019年06月21日
在主题设置里面有开启了,但是显示出错~~没有行号和字体格式也不大对
评论头像
猫叔 2019年06月30日
这个标题差点要绕死我了,读了半天!
评论头像
free徐来、 2019年07月20日
prettify文件怎么使用呢
评论头像
专收爆米花 博主 2019年07月21日
文章已经有说明
评论头像
www 2019年09月19日
我看了你的新文档,这些都是有加的,后台也开启了代码高亮,我看到你的文件也有引入文件,为什么还是不可以呢?
评论头像
专收爆米花 博主 2019年09月22日
<pre class="prettyprint linenums"> 代码 </pre>
评论头像
www 2019年09月24日
已经加过了,但是如果分类目录里面只有一篇文章可以生效,如果2个文章在一个目录就没有效果了
评论头像
asdasd 2020年04月23日
asda

发表评论

表情 颜文字
插入代码