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


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

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

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

  1. add_filter( 'the_content', 'pre_content_filter', 0 );
  2. /**
  3. * 转换pre标签中的html代码
  4. *
  5. * 使用'the_content'钩子.
  6. *
  7. * @author c.bavota
  8. */
  9. function pre_content_filter( $content ) {
  10. return preg_replace_callback( '|<pre.*>(.*)</pre|isU' , 'convert_pre_entities', $content );
  11. }
  12.  
  13. function convert_pre_entities( $matches ) {
  14. return str_replace( $matches[1], htmlentities( $matches[1] ), $matches[0] );
  15. }
  16.  

然后我们新建文章添加如下代码:
<pre>
<!DOCTYPE HTML>
<html>
<head>
<meta charset=”UTF-8″>
</head>
<body>
Test html.
</body>
</html>
</pre>
最终效果如下图:
prehtml