I use the below code to delete custom posts with status ‘expired’ (thanks to Jamie Keefer). Posts are set as ‘expired’ by a 3rd party plugin. Users have only a frontend access to their posts (adverts).
My question is: how to delete them after a number of days after they expired if post authors don’t republish them? Also, I will appreciate any suggestions about how to improve this code.
// expired_post_delete hook fires when the Cron is executed
add_action( 'expired_post_delete', 'delete_expired_posts' );
// This function will run once the 'expired_post_delete' is called
function delete_expired_posts() {
$todays_date = current_time('mysql');
$args = array(
'post_type' => 'advert',
'post_status' => 'expired',
'posts_per_page' => -1
);
$posts = new WP_Query( $args );
// The Loop
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
wp_delete_post(get_the_ID());
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
}
// Add function to register event to WordPress init
add_action( 'init', 'register_daily_post_delete_event');
// Function which will register the event
function register_daily_post_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'expired_post_delete' ) ) {
// Schedule the event
wp_schedule_event( time(), 'daily', 'expired_post_delete' );
}
}
UPDATE
This is how posts are set as ‘expired’:
add_action( 'adverts_event_expire_ads', 'adverts_event_expire_ads' );
/**
* Expires ads
*
* Function finds Adverts that already expired (value in _expiration_date
* meta field is lower then current timestamp) and changes their status to 'expired'.
*
* @since 0.1
* @return void
*/
function adverts_event_expire_ads() {
// find adverts with status 'publish' which exceeded expiration date
// (_expiration_date is a timestamp)
$posts = new WP_Query( array(
"post_type" => "advert",
"post_status" => "publish",
"meta_query" => array(
array(
"key" => "_expiration_date",
"value" => current_time( 'timestamp' ),
"compare" => "<="
)
)
) );
if( $posts->post_count ) {
foreach($posts->posts as $post) {
// change post status to expired.
$update = wp_update_post( array(
"ID" => $post->ID,
"post_status" => "expired"
) );
} // endforeach
} // endif
}