WordPress编辑器添加自定义pre标签

2021年6月11日 1455点热度 0人点赞 0条评论

我们知道使用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.接着继续在后边添加如下代码:

<code>//添加HTML编辑器自定义快捷标签Pre按钮
add_action('after_wp_tiny_mce', 'add_button_mce');
function add_button_mce($mce_settings) {
?&gt;
&lt;script type="text/javascript"&gt;
QTags.addButton( 'hr', 'hr', "\n&lt;hr /&gt;\n", "" );
QTags.addButton( 'h1', 'h1', "\n&lt;h1&gt;", "&lt;/h1&gt;\n" );
QTags.addButton( 'h2', 'h2', "\n&lt;h2&gt;", "&lt;/h2&gt;\n" );
QTags.addButton( 'h3', 'h3', "\n&lt;h3&gt;", "&lt;/h3&gt;\n" );
QTags.addButton( 'pre', '代码高亮', '&lt;pre class="prettyprint linenums"&gt;\n', "\n&lt;/pre&gt;" );
&lt;/script&gt;
&lt;?php
}</code>

小小调酒师

此刻打盹,你将做梦; 此刻学习,你将圆梦。 个人邮箱:shellways@foxmail.com

文章评论