Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.