WordPress 如何在文章和评论中插入代码

2017-01-15 06:44 2,509 39 条评论 龙笑天下
Dragon主题购买

Wordpress 如何在文章和评论中插入代码

如果不使用插件的话,在文章中和评论中是无法插入一些 PHP、CSS、HTML、JS 等代码的,就算使用了codepre标签也不行...因为 wordpress 自身有一个强大的 HTML 标签过滤系统,你插入的 html 标签会直接消失~~

本文将介绍如何在文章及评论中使用code标签来插入代码。

/**
 * WordPress 如何在文章和评论中插入代码 - 龙笑天下
 * https://www.ilxtx.com/html-entities-of-code-fragments-in-posts-and-comments.html
 */
add_filter('pre_comment_content', 'lxtx_encode_code_in_posts_comments');
add_filter('the_content', 'lxtx_encode_code_in_posts_comments');
function lxtx_encode_code_in_posts_comments($source) {
  $encoded = preg_replace_callback('/<code>(.*?)<\/code>/ims',
  create_function(
    '$matches',
    '$matches[1] = preg_replace(
        array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "",
        $matches[1]);
      return "<code>" . esc_html( $matches[1] ) . "</code>";'
  ),
  $source);
  if ($encoded)
    return $encoded;
  else
    return $source;
}

代码改自《Automatically Escape HTML Entities of Code Fragments in Comments (WordPress)

将上面的代码加入 functions.php 中,然后使用 <code></code> 来插入代码即可!

其它参考文章及代码

「点点赞赏,手留余香」

还没有人赞赏,快来当第一个赞赏的人吧!

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

2017-01-01

2017-02-05

发表评论

表情 格式 贴图 链接 私密 签到
Dragon主题购买阿里云特价云服务器1核2G低至86元,N4共享型服务器3年仅需799元腾讯云特价云服务器1核2G 88元/年 2核4G3M688元/3年,更有千元代金券礼包免费领!
评论
正在努力加载中...
扫一扫二维码分享
×
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies. Learn more