【问题标题】:WordPress - Add tags taxonomy to commentsWordPress - 为评论添加标签分类
【发布时间】:2016-06-13 03:19:41
【问题描述】:

我正在做一个项目,该项目要求 cmets 具有标签并且可以通过标签进行搜索。有没有办法在 WP 中实现它,或者我应该寻找一些解决方法(比如创建子帖子类型而不是 cmets 并对其应用标签)?

如果有,我该怎么做?

谢谢。

【问题讨论】:

    标签: wordpress tags comments


    【解决方案1】:

    您可以使用评论元来存储和检索特定评论的标签。

    首先,将标签字段添加到评论表单并填充标签。以下代码将在注释文本区域之后立即添加一个“选择”字段并使用标签填充它。

    add_filter( 'comment_form_defaults', 'change_comment_form_defaults');
    function change_comment_form_defaults( $default ) {
        $commenter = wp_get_current_commenter();
        $out = '<label for="comment_tags">Tags:</label><select name="comment_tags" multiple>';
        foreach ( get_tags() as $tag ) {
            $out .= '<option value="<?php echo $tag->term_id; ?>"><?php echo $tag->name; ?></option>';
        }
        $out .= '</select>';
        $default[ 'comment_field' ] .= $out;
        return $default;
    }
    

    comment_post 操作在评论存储到数据库后立即触发。您可以使用它来存储帖子元数据。

    add_action('comment_post', 'add_tags_to_comment', 10, 2);
    function add_tags_to_comment( $comment_ID, $comment_approved ) {
        foreach($_POST["comment_tags"] as $comment_tag) {
            add_comment_meta( $comment_ID, "comment_tag", $comment_tag );
        }
    }
    

    我更喜欢将每个标签存储为单独的记录,而不是将所选标签存储为单个记录中的数组。这将更容易根据标签搜索 cmets。

    当你想检索评论的标签时,你可以get_comment_meta

    $tags = get_comment_meta($comment_ID, "comment_tag");
    foreach($tags as $tag_id) {
        $tag_term = get_term($tag_id, 'post_tag');
        echo $tag_term->name;
    }
    

    使用 WP_Comment_Query 根据标签搜索 cmets。

    $tags = array(1,32,5,4); /* Replace it with tags you want to search */
    $args = array(
        'meta_query' => array(
            array(
                'key' => 'comment_tag',
                'value' => $tags,
                'compare' => 'IN'
            )
        )
     );
    $comment_query = new WP_Comment_Query( $args );
    

    希望这对您有所帮助。

    【讨论】:

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