Skip to main content
Login Join
Snippet · PHP

Automatically Expire Posts on a Scheduled Date

Shared by Amit Dholiya · August 3, 2026 · @wpfolks_daily_post_expiry

1 copy
17 views
Back to Snippets

This snippet allows you to automatically change a published post to Draft after a specified expiration date stored in a custom field named post_expiry_date. It’s useful for job listings, promotions, announcements, events, and time-sensitive content.

Steps

  1. Open your active theme’s functions.php file or a custom functionality plugin.
  2. Add the code below.
  3. Save the file.
  4. Add a custom field named post_expiry_date to any post using the format YYYY-MM-DD (e.g., 2026-12-31).
  5. Once the date has passed, the post will automatically become a draft when WordPress runs its scheduled cron events.

Benefits

/**
 * Expire posts based on a custom field date.
 */
function wpfolks_expire_scheduled_posts() {

    $posts = get_posts(
        array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_key'       => 'post_expiry_date',
            'meta_compare'   => 'EXISTS',
        )
    );

    $today = current_time( 'Y-m-d' );

    foreach ( $posts as $post ) {

        $expiry = get_post_meta( $post->ID, 'post_expiry_date', true );

        if ( ! empty( $expiry ) && $expiry <= $today ) {

            wp_update_post(
                array(
                    'ID'          => $post->ID,
                    'post_status' => 'draft',
                )
            );
        }
    }
}

function wpfolks_schedule_post_expiry() {

    if ( ! wp_next_scheduled( 'wpfolks_daily_post_expiry' ) ) {
        wp_schedule_event( time(), 'daily', 'wpfolks_daily_post_expiry' );
    }
}
add_action( 'wp', 'wpfolks_schedule_post_expiry' );
add_action( 'wpfolks_daily_post_expiry', 'wpfolks_expire_scheduled_posts' );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments