如果不使用插件的话,在文章中和评论中是无法插入一些PHP、CSS、HTML、JS等代码的,就算使用了code或pre标签也不行…因为wordpress自身有一个强大的HTML标签过滤系统,你插入的html标签会直接消失~~
本文将介绍如何在文章及评论中使用pre标签来插入代码。
/**
* WordPress如何在文章和评论中插入代码 - 天赐网络
* http://www.vlwx.com/111.html
*/
add_filter('pre_comment_content', 'yyob_encode_code_in_posts_comments');
add_filter('the_content', 'yyob_encode_code_in_posts_comments');
function yyob_encode_code_in_posts_comments($source) {
$encoded = preg_replace_callback('/<pre>(.*?)<\/pre>/ims',
create_function(
'$matches',
'$matches[1] = preg_replace(
array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "",
$matches[1]);
return "<pre>" . esc_html( $matches[1] ) . "</pre>";'
),
$source);
if ($encoded)
return $encoded;
else
return $source;
}
将上面的代码加入主题的functions.php文件中,然后使用<pre></pre>来插入代码即可!