Function to check if author has posted within the last x days

Is is possible to check whether an author has posted in the last X days?

I am currently using this function to determine whether he has posted at all.

$args = array(
    'post_type'  => 'your_custom_post_type',
    'author'     => get_current_user_id(),
);

$wp_posts = get_posts($args);

if (count($wp_posts)) {
    echo "Yes, the current user has 'your_custom_post_type' posts published!";
} else {
    echo "No, the current user does not have 'your_custom_post_type' posts published.";
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes, it is possible and it is pretty small change in your code…

get_posts() uses WP_Query, so you can use all params from this list: https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

So here’s your code after changes:

$args = array(
    'post_type'  => 'your_custom_post_type',
    'author'     => get_current_user_id(),
    'date_query' => array(
        array(
            'after'     => '- X days', // <- change X to number of days
            'inclusive' => true,
        ),
     ),
     'fields' => 'ids', // you only want the count of posts, so it will be much nicer to get only IDs and not all contents from DB
);

$wp_posts = get_posts($args);

if (count($wp_posts)) {
    echo "Yes, the current user has 'your_custom_post_type' posts published!";
} else {
    echo "No, the current user does not have 'your_custom_post_type' posts published.";
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x