How to make sure WP-CRON job loops through all posts?
I am using WP-Crontrol and have some CRON jobs running daily to check the age of the posts. If the post is 2 days older, they will be deleted.
This works but for some reason, only some of the three days and older posts get deleted. There are still some that remain published.
It must be because there are a lot of posts on the site around 3000. Is there a way to make my CRON job more efficient?
Here is the current code that I have running:
class EventsWPCron {
public function __construct() {
if ( ! wp_next_scheduled( 'trash_old_events' ) ) {
wp_schedule_event( time(), 'daily', 'trash_old_events' );
}
add_action( 'trash_old_events', array( $this, 'delete_events' ) );
}
public function delete_events() {
$args = array(
'post_type' = 'event',
'post_status' = 'publish',
'posts_per_page' = -1,
'date_query' = array(
array(
'before' = '2 days ago'
)
)
);
$query = new WP_Query( $args );
$posts = $query-get_posts();
foreach( $posts as $post ) {
wp_delete_post( $post-ID, true );
}
}
}
new EventsWPCron();