Web

让wordpress评论支持更多的html标签

michaelliunsky · 10月1日 · 2023年 · · · 本文共992个字 · 预计阅读4分钟294次已读

题外话

说来惭愧,又好久没有更新博客了,最近忙着月考,一直没时间来管。今天突然想起1个月之前主题开发中遇到的问题,这里来跟大家分享一下解决方案。

代码

这是代码的两个版本。 第一个允许插入一个html标签,第二个将您希望批量添加到 $allowedtags 全局变量的多个html标签合并。

添加一个标签

要将一个标签添加到 $allowedtags 函数,请使用这一个代码片段。 这里我们允许img标签带有src和alt属性。

add_action('pre_comment_on_post', 'add_post_comment_html_tags' );
function add_post_comment_html_tags( $commentdata ) {

  global $allowedtags;

  $allowedtags['img'] = [
    'src'=> true,
    'alt'=> true
  ];

}

批量添加标签

要添加多个标签,请使用此版本。 这里我们添加带有 src 和 alt 属性的 img 标签以及 pre 标签。

add_action('pre_comment_on_post', 'add_post_comment_html_tags' );
function add_post_comment_html_tags( $commentdata ) {

  global $allowedtags;

  $new_tags = [
    'img'=> [
      'src'=> true,
      'alt'=> true
    ],
    'pre'=> []
  ];

  $allowedtags = array_merge( $allowedtags, $new_tags );

}

WordPress允许的默认标签列表

这是WordPress Core 允许的html标签列表。所以如果它不在这个列表中,默认情况下是不允许的。 使用上面的代码片段可以包含更多标签。

  • a tag
    • href attribute
    • title attribute
  • abbr tag
    • title attribute
  • acronym tag
    • title attribute
  • b tag
  • blockquote tag
    • cite attribute
  • cite tag
  • code tag
  • del tag
    • datetime attribute
  • em tag
  • i tag
  • q tag
    • cite attribute
  • s tag
  • strike tag
  • strong tag

效果展示

这样可以实现评论插入代码功能,效果如下:

让wordpress评论支持更多的html标签
0 条回应