1

How I can get all comment authors from a single post?

I am building a plugin and want to notify the author of a post when someone comment on his post but if another person adds a comment I want to notify the author of the post and the authors of the other comments on that post.

I need the emails of the post author and all the comment authors from that specific post in a array do I can send them an email.

0

Writing a loop and going through every comment is the option that I can offer you. Take a look at this example:

function get_comment_authors($post_ID){
    // Get every comment on this post
    $args = array(
        'post_id' => $post_ID
    );
    $comment_objects = get_comments( $args );
    // Define an empty array to store the comments
    $author_array = array();
    // Run a loop through every comment object
    foreach ( $comment_objects as $comment ) {
        // Get the comment's author
        $author_array[] = $comment->comment_author;
    }
    // Return the authors as an array
    return $author_array;
}

So, get_comment_authors(123); will return every author that left a comment on the post that has an ID of 123.

  • Hi small question, how to add also the post author email to the array? I tried this: // get and add post author to array $author = get_post_field( 'post_author', $post_id ); $author_mail = the_author_meta( 'user_email' , $author); $author_array[] = $author_mail; but that doesn't work because the mail is not added to the array correctly. print_r gives this mymail@me.comArray ( [0] => [1] => info@mydomein.nl ) – Maarten Heideman Jul 17 '17 at 8:02
  • Already solved it, using get_the_author_meta instead of the_author_meta – Maarten Heideman Jul 17 '17 at 12:06
  • @MaartenHeideman Hi! You can use comment_author_email, the email is already stored in the comments object. So you should use : $author_array[] = array ($comment->comment_author, $comment->comment_author_email); which will give you an array of name/email pairs, such as : (john,john@example.com),(doe,doe@example.com) and so on. – Jack Johansson Jul 17 '17 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.