代码之家  ›  专栏  ›  技术社区  ›  timm

通过在带有hashtag的注释中写入分类标记,将其添加到wordpress帖子中

  •  0
  • timm  · 技术社区  · 7 年前

    在wordpress中,我有一篇带有一些标签的帖子。用户应该能够通过在评论中使用hashtag写入标记来向帖子添加标记,例如,“这是一条添加#橙色的评论”应该添加标记橙色。

    这是我的代码:

    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 如果有“这是一条添加了#橘子的评论”这样的文字,那么它就起作用了。但是,当我写实际的评论时,它不起作用,我不知道原因。有人能帮我吗?

    3 回复  |  直到 7 年前
        1
  •  1
  •   Sco    7 年前
        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;
        }
    
        2
  •  0
  •   timm    7 年前

    我找到了一个基于 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
  •  -1
  •   Ivar    7 年前

    $comment = get_comment($comment_ID); 
    

    具有

    $comment = get_comments($comment_ID);