wordpress使用pre标签来显示你的HTML

2020-08-30 11:45:57

我们在使用wordpress建立自己的博客时,经常需要对我们的代码进行高亮处理,当然我们可以使用插件来实现,例如以下几款插件:

wordpress代码高亮插件:WP Code Highlight
SyntaxHighlighter Evolved
wp-syntax

当然我们有时候很不喜欢用插件,毕竟插件还是影响了wordpress的性能,那我们就用代码来实现:
在我们主题的functions.php文件添加如下代码:


add_filter( 'the_content', 'pre_content_filter', 0 );
/**
* 转换pre标签中的html代码
*
* 使用'the_content'钩子.
*
* @author c.bavota
*/
function pre_content_filter( $content ) {
return preg_replace_callback( '|

(.*)</pre|isU' , 'convert_pre_entities', $content );}function convert_pre_entities( $matches ) {return str_replace( $matches[1], htmlentities( $matches[1] ), $matches[0] );}

然后我们新建文章添加如下代码:








Test html.


最终效果如下图:
prehtml