0

I want to compare the date of a user's last two posts. I'm new to WordPress developing. I have written this code but I'm not sure if it's correct. Please help me in correcting it:

$ID                  = $post->ID;
$user_id             = $post->post_author;
$author_recent_posts = get_most_recent_post_of_user( $user_id );
$last_post_id        = $author_recent_posts[1]->post_id;
$last_post           = get_post($last_post_id);
$last_post_date      = $last_post->post_date;
$post_date           = $post->post_date;

if ( $post_date - $last_post_date > 24*60*60 )
    return;
0

According to the codex, you're manipulating get_most_recent_post_of_user()'s returned value the wrong way. get_most_recent_post_of_user() directly returns the post_date_gmt among blog_id, post_id, and post_gmt_ts.

Anyway, if you want to get the 2 last posts of a specific author, use WP_Query instead, which should by default get last posts in the order you need.

$author_id = $author_id;

$args = array(
    'post_type'      => 'post',
    'author'         => $author_id,
    'posts_per_page' => 2,
);

$query      = new WP_Query( $args );
$last_posts = $query->get_posts(); /*Array of post objects*/

Now, you've got only the 2 last WP_Post objects accessible this way:

$last_post        = $last_posts[0]; /*The most recent post object*/
$second_last_post = $last_posts[1]; /*The second most recent post object*/

If you still need to compare the 2 last post's dates:

$last_post_date        = $last_post->post_date_gmt;
$second_last_post_date = $second_last_post->post_date_gmt;

Note that we now have 2 GMT string dates to deal with. For your comparaison, we'll convert them to timestamp:

$last_post_date        = strtotime( $last_post_date );
$second_last_post_date = strtotime( $second_last_post_date );

if ( ( $last_post_date - $post_date ) > 86400 )
    return;

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.