我们知道使用WordPress撰写文章时有两种模式可视化和文本两种模式,一般需要在文章中展示代码,则需要在可视化模式下粘贴代码,这样在切换到文本模式时会自动转义。若直接在文本模式下贴代码那么就会被直接运行,显示出来的就不是正常的代码了。
1.下面这个过滤器可以让那些被pre标签包住的代码在文本模式下不会被直接运行,而在可视化下依然保持正常状态。这样每次贴代码就不需要切换到可视化模式了。非常方便。
/* * WordPress Pre标签内的html不转义 */ add_filter( 'the_content', 'pre_content_filter', 0 ); function pre_content_filter( $content ) { return preg_replace_callback( '|<pre.*>(.*)</pre|isU' , 'convert_pre_entities', $content ); } function convert_pre_entities( $matches ) { return str_replace( $matches[1], htmlentities( $matches[1] ), $matches[0] ); }
添加到主题的functions.php里面即可。
2.接着继续在后边添加如下代码:
//添加HTML编辑器自定义快捷标签Pre按钮
add_action('after_wp_tiny_mce', 'add_button_mce');
function add_button_mce($mce_settings) {
?>
<script type="text/javascript">
QTags.addButton( 'hr', 'hr', "\n<hr />\n", "" );
QTags.addButton( 'h1', 'h1', "\n<h1>", "</h1>\n" );
QTags.addButton( 'h2', 'h2', "\n<h2>", "</h2>\n" );
QTags.addButton( 'h3', 'h3', "\n<h3>", "</h3>\n" );
QTags.addButton( 'pre', '代码高亮', '<pre class="prettyprint linenums">\n', "\n</pre>" );
</script>
<?php
}
文章评论