// Schedule the event on plugin activation
function wbcom_stories_activation() {
if ( ! wp_next_scheduled( 'wbcom_stories_delete_old_posts' ) ) {
wp_schedule_event( time(), 'daily', 'wbcom_stories_delete_old_posts' );
}
}
register_activation_hook( __FILE__, 'wbcom_stories_activation' );
// Clear the scheduled event on plugin deactivation
function wbcom_stories_deactivation() {
$timestamp = wp_next_scheduled( 'wbcom_stories_delete_old_posts' );
wp_unschedule_event( $timestamp, 'wbcom_stories_delete_old_posts' );
}
register_deactivation_hook( __FILE__, 'wbcom_stories_deactivation' );
// Hook the function to the scheduled event
add_action( 'wbcom_stories_delete_old_posts', 'wbcom_delete_old_wp_stories_posts' );
function wbcom_delete_old_wp_stories_posts() {
$post_types = array( 'wb-story', 'wb-story-box', 'wb-user-story' );
$days = 7; // Number of days
foreach ( $post_types as $post_type ) {
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1,
'post_status' => 'any',
'date_query' => array(
'column' => 'post_date_gmt',
'before' => date( 'Y-m-d', strtotime( "-$days days" ) )
),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Get the post ID
$post_id = get_the_ID();
// Delete associated media
$attachments = get_attached_media( '', $post_id );
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true );
}
// Delete the post
wp_delete_post( $post_id, true );
}
}
wp_reset_postdata();
}
}
Comments