# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: content-expiry, cron, categories
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/content-unpublish-category-after-days/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Move Posts in a Category Back to Draft After a Number of Days" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
