Wordpress - Add Expiry Post Status and Cron Task to Expire Posts after X Days
<?php
// Register Expired Post Status //
function register_expired() {
register_post_status( 'expired', array(
'label' => _x( 'Expired', 'post' ),
'label_count' => _n_noop( 'Expired Post <span class="count">(%s)</span>', 'Expired <span class="count">(%s)</span>' ),
'show_in_admin_status_list' => true
));
}
add_action( 'init', 'register_expired' );
// Schedule Daily Cronjob //
function daily_cron_activation() {
if ( !wp_next_scheduled( 'daily_cron' ) ) {
wp_schedule_event( current_time( 'timestamp' ), 'twicedaily', 'daily_cron' );
}
}
add_action( 'wp', 'daily_cron_activation' );
// Expiry Posts that are older than (30) days //
function expire_posts() {
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => -1
));
if ( $query -> have_posts() ) {
while ( $query -> have_posts() ) {
$query -> the_post();
// Amount of time to wait until expiry //
$time = '-30 days';
if ( strtotime( get_the_date() ) <= strtotime( date( 'F j, Y' ) . $time ) ) {
wp_update_post( array(
'id' => $post->ID,
'post_status' => 'expired'
));
}
}
}
}
add_action( 'daily_cron', 'expire_posts' );
// Cron Deactivation //
function daily_cron_deactivation() {
wp_clear_scheduled_hook( 'daily_cron' );
}
register_deactivation_hook( __FILE__, 'daily_cron_deactivation' );
?>