Advertisement
vapvarun

Delete stories and their media after 7 days

Aug 1st, 2024
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.91 KB | Software | 0 0
  1. // Schedule the event on plugin activation
  2. function wbcom_stories_activation() {
  3.     if ( ! wp_next_scheduled( 'wbcom_stories_delete_old_posts' ) ) {
  4.         wp_schedule_event( time(), 'daily', 'wbcom_stories_delete_old_posts' );
  5.     }
  6. }
  7. register_activation_hook( __FILE__, 'wbcom_stories_activation' );
  8.  
  9. // Clear the scheduled event on plugin deactivation
  10. function wbcom_stories_deactivation() {
  11.     $timestamp = wp_next_scheduled( 'wbcom_stories_delete_old_posts' );
  12.     wp_unschedule_event( $timestamp, 'wbcom_stories_delete_old_posts' );
  13. }
  14. register_deactivation_hook( __FILE__, 'wbcom_stories_deactivation' );
  15.  
  16. // Hook the function to the scheduled event
  17. add_action( 'wbcom_stories_delete_old_posts', 'wbcom_delete_old_wp_stories_posts' );
  18.  
  19. function wbcom_delete_old_wp_stories_posts() {
  20.     $post_types = array( 'wb-story', 'wb-story-box', 'wb-user-story' );
  21.     $days = 7; // Number of days
  22.  
  23.     foreach ( $post_types as $post_type ) {
  24.         $args = array(
  25.             'post_type'      => $post_type,
  26.             'posts_per_page' => -1,
  27.             'post_status'    => 'any',
  28.             'date_query'     => array(
  29.                 'column' => 'post_date_gmt',
  30.                 'before' => date( 'Y-m-d', strtotime( "-$days days" ) )
  31.             ),
  32.         );
  33.  
  34.         $query = new WP_Query( $args );
  35.  
  36.         if ( $query->have_posts() ) {
  37.             while ( $query->have_posts() ) {
  38.                 $query->the_post();
  39.  
  40.                 // Get the post ID
  41.                 $post_id = get_the_ID();
  42.  
  43.                 // Delete associated media
  44.                 $attachments = get_attached_media( '', $post_id );
  45.                 foreach ( $attachments as $attachment ) {
  46.                     wp_delete_attachment( $attachment->ID, true );
  47.                 }
  48.  
  49.                 // Delete the post
  50.                 wp_delete_post( $post_id, true );
  51.             }
  52.         }
  53.         wp_reset_postdata();
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement