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
- Open your active theme’s
functions.phpfile or a custom functionality plugin. - Add the code below.
- Save the file.
- Add a custom field named
post_expiry_dateto any post using the format YYYY-MM-DD (e.g.,2026-12-31). - Once the date has passed, the post will automatically become a draft when WordPress runs its scheduled cron events.
Benefits
- Automatically expires time-sensitive content.
- Ideal for events, offers, and job listings.
- No manual intervention required.
- Uses WordPress Cron for automation.
- Lightweight solution without a plugin.
/**
* 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' );