【问题标题】:Adding a taxonomy tag to wordpress post by writing it in comment with hashtag通过在带有主题标签的评论中写入分类标签,将分类标签添加到 wordpress 帖子
【发布时间】:2017-11-09 07:29:10
【问题描述】:

在 wordpress 中,我有一个带有一些标签的帖子。用户应该能够通过在评论中编写带有井号标签的标签来为帖子添加标签,例如“这是添加#orange 的评论”应添加标记橙色。

这是我的代码:

function add_tag_from_comment( $comment_ID ) {
    $comment = get_comment($comment_ID);
    $search_text = strip_tags( str_replace( array( "\n", "\r"), $comment->comment_content));
    preg_match_all('/#([\d\w-_]+)[\b|]{0,3}/', $search_text, $matches, PREG_PATTERN_ORDER);
    foreach($matches[1] as $match) {
        wp_set_post_tags( $comment->comment_post_ID, $match, true );
    }
}
add_action( 'comment_post', 'add_tag_from_comment', 10, 2 );

如果我将$comment->comment_content 替换为“这是添加#oranges 的评论”之类的文本,那么它可以工作。但是当我写实际评论时它不起作用,我不知道原因。有人可以帮帮我吗?

【问题讨论】:

  • 检查 $comment (echo $comment) 的内容,可能是数据以某种方式被斜切或编码,正则表达式无法捕获内容中的主题标签。跨度>
  • 感谢您的提示。不幸的是,我无法访问日志文件或控制台。有没有其他方法可以调试和显示评论内容?

标签: php wordpress comments taxonomy


【解决方案1】:
    add_action('comment_post', 'tag_comment_insert', 2);
    function tag_comment_insert($comment) {
      $comment_text = get_comment_text($comment);
      preg_match_all('/#([0-9a-zA-Z]+)/', $comment_text, $matches, PREG_PATTERN_ORDER);
      wp_set_post_tags( $comment, $matches[1], true );
    }

    add_action('comment_text', 'tag_comment', 2);
    function tag_comment($comment) {
      $comment = preg_replace('/#([0-9a-zA-Z]+)/i', '<a class="hashtag" href="'.get_home_url().'/tag/$1">#$1</a>', $comment);
      return $comment;
    }

【讨论】:

  • 谢谢。第二个功能有效,但在我的情况下第一个无效。该标签被添加到通用标签列表中,但未链接到帖子。你对此有什么解释吗?
  • 我缩小了问题的范围。如果我使用帖子的 id,例如wp_set_post_tags(12, $matches[1], true);,然后标签被添加到帖子中。使用 $comment$comment-&gt;comment_post_ID 不起作用。
【解决方案2】:

我找到了一个基于Sco's Answer的解决方案:

add_action('comment_post', 'tag_comment_insert', 2);
function tag_comment_insert($comment) {
    $comment_text = get_comment_text($comment);
    $current_comment = get_comment( $comment );
    $comment_post_id = $current_comment->comment_post_ID;
    preg_match_all('/#([\d\w-_]+)[\b|]{0,3}/', $comment_text, $matches, PREG_PATTERN_ORDER);
    wp_set_post_tags( $comment_post_id, $matches[1], true );
}

add_action('comment_text', 'tag_comment', 2);
function tag_comment($comment) {
    $comment = preg_replace('/#([0-9a-zA-Z]+)/i', '<a class="hashtag" href="'.get_home_url().'/tag/$1">#$1</a>', $comment);
    return $comment;
}

之前的问题是post_ID没有设置。我的解决方案似乎有点复杂,因此感谢任何缩短。谢谢大家的帮助。

【讨论】:

    【解决方案3】:

    替换

    $comment = get_comment($comment_ID); 
    

    $comment = get_comments($comment_ID);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2020-01-21
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多