elkah
elkah

Reputation: 141

WordPress - Add tags taxonomy to comments

I'm working on a project that requires comments to have tags and be searchable by tags. Is there a way to implement it in WP, or should I look for some workaround (like create child post type instead of comments and apply tags to it)?

If there is, how can I do it?

Thank you.

Upvotes: 1

Views: 560

Answers (1)

Shahul Hameed
Shahul Hameed

Reputation: 103

You can use comment meta to store and retrieve tags of a particular comment.

First of all, add the tag field to the comment form and populate the tags. The following code will add a "select" field immediately after comment textarea and populate it with the tags.

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;
}

The comment_post action is triggered immediately after a comment is stored in the database. You can use it to store post meta.

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 );
    }
}

Instead of storing the selected tags as an array in a single record, I prefer to store each tag as a separate record. This will make it easier to search the comments based on tags.

When you want to retrieve the tags of a comment, You can 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;
}

Use WP_Comment_Query to search comments based on tags.

$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 );

Hope this helped you.

Upvotes: 1

Related Questions