0

I want to get the last post date was written by the user and here's the code that I have made but it's not working:

function get_user_last_post_date( $user_id ) {

    $args = array(
        'post_author' => $user_id,
        'post_type' => 'any',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'order' => 'DESC',
        'orderby ' => 'post_date'
    );
    $latest_posts = new WP_Query( $args );

    $last_date = '';
    if ( $latest_posts->have_posts() ) {
        $last_date = $latest_posts;
    }

    return $last_date;
}

1 Answer 1

0

In your sample code the $latest_posts is an instance of WP_Query class. If you want to get the latest post's date, you should do this:

$latest_posts = new WP_Query( $args );

$last_date = '';
if ( $latest_posts->have_posts() ) {
   $latest_posts->the_post();
   $last_date = get_the_date();
}

return $last_date;
9
  • I got a error: Notice: Trying to get property 'post_date' of non-object
    – John
    Dec 26, 2019 at 15:57
  • Your code is not correct it's not getting the latest post date was written by the user
    – John
    Dec 26, 2019 at 16:02
  • Sorry, I made a mistake in my code. I've edited my answer.
    – Had1z
    Dec 26, 2019 at 16:09
  • It's getting the date of the first post not the latest post.
    – John
    Dec 26, 2019 at 16:11
  • @John, WP_Query has default values for order and orderby parameters, and it's default values will sort posts by date in a way that the latest posts come first. So remove these two parameters from $args
    – Had1z
    Dec 26, 2019 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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