Move Posts in a Category Back to Draft After a Number of Days
Automatically unpublishes posts in a chosen category, such as Jobs, Offers or Events, once they are older than a set number of days, so stale listings disappear on their own.
Opens WPIDE on
Code
// Category slug, age in days and the status to set.
$wpide_expire_category = 'jobs';
$wpide_expire_days = 30;
$wpide_expire_status = 'draft';
add_action( 'init', function () {
if ( ! wp_next_scheduled( 'wpide_expire_category_posts' ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'twicedaily', 'wpide_expire_category_posts' );
}
} );
add_action( 'wpide_expire_category_posts', function () use ( $wpide_expire_category, $wpide_expire_days, $wpide_expire_status ) {
$ids = get_posts( array(
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => $wpide_expire_category,
'posts_per_page' => 50,
'fields' => 'ids',
'no_found_rows' => true,
'date_query' => array( array( 'before' => $wpide_expire_days . ' days ago' ) ),
) );
foreach ( $ids as $id ) {
wp_update_post( array( 'ID' => $id, 'post_status' => $wpide_expire_status ) );
}
} );
Notes
Runs twice a day in batches of 50; posts are set to draft, not deleted, so nothing is lost.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.