I would suggest you use wp_schedule_event()
and create a custom hook that you trigger daily. This hook can then call a custom function in which you query posts with the desired publish date, and change their status.
For example, create a new plugin and add (note: I have not tested this):
// Schedule auto-drafting post event on plugin activation.
register_activation_hook( __FILE__, 'schedule_auto_draft_posts' );
add_action( 'auto_draft_posts', 'draft_posts' );
function schedule_auto_draft_posts() {
wp_schedule_event( time(), 'daily', 'auto_draft_posts' );
}
// Draft published posts based on the post's publish date.
function draft_posts() {
$old_status="publish";
$new_status="draft";
// Example: get published posts made before last week.
$posts = get_posts(
array(
'date_query' => array(
array(
'column' => 'post_date_gmt',
'before' => '1 week ago',
),
),
'fields' => 'all',
'numberposts' => -1,
'post_status' => $old_status,
)
);
foreach ($posts as $post) {
// Update the post status.
wp_update_post(
'ID' => $post->ID,
'status' => $new_status,
);
// Fire actions related to the transitioning of the post's status.
wp_transition_post_status( $new_status, $old_status, $post );
}
}
// Clean the scheduler on plugin deactivation.
register_deactivation_hook( __FILE__, 'unschedule_auto_draft_posts' );
function unschedule_auto_draft_posts() {
wp_clear_scheduled_hook( 'auto_draft_posts' );
}
Documentation:
- Understanding WP-Cron Scheduling
- If you would like to retrieve posts with your own date query, you could use PHP’s relative date formats.
Documentation of the functions used: