I am trying to get whether the author has posted within the last 30 days but this returns TRUE even if the author hasn't posted within the last 30 days.
<?php $args = array(
'post_type' => 'post',
'post_status' => 'publish',
'author' => get_current_user_id(),
'date_query' => array(array('after' => date('Y-m-d', strtotime('-30 days')), 'inclusive' => true,),)
, 'fields' => 'ids',);
$wp_posts = get_posts($args);
if(count($wp_posts)) : ?>
<div>Author posted within the last 30 days</div>
<?php else : ?>
<div>Author did not post within the last 30 days</div>
<?php endif; ?>
Not sure what I am doing wrong here.
This question already has an answer here: Function to check if author has posted within the last x days (1 answer) Closed 6 years ago.I am trying to get whether the author has posted within the last 30 days but this returns TRUE even if the author hasn't posted within the last 30 days.
<?php $args = array(
'post_type' => 'post',
'post_status' => 'publish',
'author' => get_current_user_id(),
'date_query' => array(array('after' => date('Y-m-d', strtotime('-30 days')), 'inclusive' => true,),)
, 'fields' => 'ids',);
$wp_posts = get_posts($args);
if(count($wp_posts)) : ?>
<div>Author posted within the last 30 days</div>
<?php else : ?>
<div>Author did not post within the last 30 days</div>
<?php endif; ?>
Not sure what I am doing wrong here.
Actually your function works as you described.
I copied your function into a page template on my site without modifying it at all. I tested it with my main user, which has posted, and it said I had posted.
Then I created a dummy user that has not posted. I tested the same page and it said I had not posted. I also posted a post backdated more than 30 days, and it still said I had not posted within the last 30 days.
All of that is by design.
A couple of points to keep in mind:
You aren't specifying in your query which type of post is being retrieved. Are you sure that the user you are testing with hasn't posted any type of post? i.e. a custom post type, a page, a contact form via a plugin, etc.
Your code is also always checking the currently logged in user. Make sure that's what you want.