If x comments in a post move post to category y

If a post has 0 comments do nothing.

If a post has 1 comment move the post to category 1.

If a post has 2 comments move the post to cayegory 2.

If a post has 3 comments or more move to category x.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could use the wp_insert_comment action to detect when new comments are added to a post. Then on your action callback, you’d the post’s comment count with get_comments_number(), and change post categories with wp_set_object_terms().

Something along these lines,

add_filter(
    'wp_insert_comment',
    function($id, $comment) {
        if ( (int) $comment->comment_approved ) {
            $post_id = (int) $comment->comment_post_ID;
            $post_comment_count = get_comments_number(
                $post_id
            );

            if ( $post_comment_count > 3 ) {
                wp_set_object_terms(
                    $post_id, 
                    array('3-comments'), 
                    'category', 
                    false // don't append, overwrite terms
                );
            } else if ( $post_comment_count === 2 ) {
                wp_set_object_terms(
                    $post_id, 
                    array('2-comments'), 
                    'category', 
                    false // don't append, overwrite terms
                );
            } else {
                wp_set_object_terms(
                    $post_id, 
                    array('1-comment'), 
                    'category', 
                    false // don't append, overwrite terms
                );
            }
        }
    },
    10,
    2
);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x