Is there a wordpress function like -

If someone recently commented in one of my posts (not other author post), I want his/her ID?

If there is no function like that, how can I achieve it?

Actually, I am building a notification system and it will be something like this

UserName is commented on your postTitle.

  • how do you define "recently" ? it's a certain amount of time like "last two weeks" ? – mmm Mar 22 '18 at 7:36
  • Probably, checking the latest comment. Time is optional and it is OK for me to check if someone comment under my post within a day or a week or a certain time. Because I want the comment author's ID. – Jamille Mar 22 '18 at 7:39

It seems you have to check with a current user.

As it's a notification system, you'll have to take all post Ids by current user and check it globally.

Otherwise, you have to check in every single post. And you will not able to access the values from anywhere of the website.

So this is the codes to get the latest (comment, comment user id) ... globally :)

// Grab all posts' (array)ids by current user
function current_author_post_ids() {

    global $current_user;

    $args = array(
        'author' => $current_user->ID,
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1
    ); // get all posts

    $author_posts = get_posts($args);

    // check if only one id return
    if (count($author_posts) > 1) {

        $allIds = array();

        foreach ($author_posts as $c_post) :
            $allIds[] = $c_post->ID;

        return $allIds;

    } else {

        return $author_posts[0]->ID;



function get_last_comment_and_author_id() {
    $args = array(
        'number' => '1',
        'post__in' => current_author_post_ids(),
        'orderby' => 'post_date',

        // order by Time Stamp Here
        // 'oderby' => 'meta_type' TIME

        'order' => 'DSC',
        'posts_per_page' => 1
    ); // get only one comment

    // Get the latest comment

    $comments = get_comments($args);

    foreach ($comments as $comment) :
        echo 'Last author ID =' . $comment->user_id . '<br>';
        echo 'Last author =' . $comment->comment_author . '<br>';
        echo 'Last Comment =' . $comment->comment_content;


To get the values, you can run this function

 <?php echo get_last_comment_and_author_id(); ?>

to retrieve the last comment of a post, you can try this code :

$comments = get_comments([
    "post_id" => $post_id,
    "number" => 1,

if (isset($comments[0])) {

    $lastComment = $comments[0];

    if ("0" === $lastComment->user_id) {
        // comment of a non connected user
    } else {
        // author identifier is in $lastComment->user_id

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.