想在wordpress 文章中插入代码,小段代码放到code里,大段代码放pre里,但是有时候想插入html代码,发现被浏览器解析了,所以我们要在输出前对代码进行转义,这样pre输出就正常了。
利用WordPress的add_filter钩子实现对文章、评论中的代码经行转义。
食用方法一
将以下code 贴到WordPress主题的funxtions.php中即可。
/**
* wordpress pre html special chars
* @author yefengs
* @link http://os.yefengs.com/wordpress-pre-tag-content-displayed-in-an-escape.html
* @var 1.0.0
* @package WordPress pre
* @subpackage yefengs
* @since 2014-12-22
* @return string */
add_filter('the_content', 'htmlspecialchars_pre', 12);
add_filter('get_comment_text', 'htmlspecialchars_pre');
function htmlspecialchars_pre ($content) {
return preg_replace_callback ("/
(.*?)/si", create_function('$matches','return "" . htmls_pecial_chars($matches[1]) ."";'),$content);
}
function htmls_pecial_chars($content=''){
//htmlspecialchars_decode()
$content = str_replace("
$content = str_replace(">",">",$content);
$content = str_replace("&","&",$content);
$content = str_replace('"',""",$content);
$content = str_replace("'","'",$content);
$content = str_replace(" "," ",$content);
return $content;
}
食用方法二
将以下code 贴到WordPress主题的funxtions.php中即可。
/**
* wordpress pre html special chars
* @author yefengs
* @link http://os.yefengs.com/
* @var 1.0.0
* @package WordPress pre
* @subpackage yefengs
* @since 2014-12-22
* @return string
*/
add_filter('the_content', 'htmlspecialchars_pre', 12);
add_filter('get_comment_text', 'htmlspecialchars_pre');
function htmlspecialchars_pre ($content) {
return preg_replace_callback ("/pre>(.*?)/si", create_function('$matches','return "
" . htmlspecialchars($matches[1]) ."";'),$content);
}