Created
          June 23, 2023 15:50 
        
      - 
      
- 
        Save NoahBohme/db975d75f89fefcc9e6d48b88b9bc3eb to your computer and use it in GitHub Desktop. 
    Script that removes products which have not been updated more than 3 months - Woocommerce
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <?php | |
| // Define the WooCommerce product age threshold in months | |
| $thresholdMonths = 3; | |
| // Get current date and time | |
| $currentDate = new DateTime(); | |
| // Setup WooCommerce query arguments | |
| $args = array( | |
| 'post_type' => 'product', | |
| 'posts_per_page' => -1, // Retrieve all products | |
| 'meta_query' => array( | |
| array( | |
| 'key' => '_wc_last_active', | |
| 'compare' => '<=', | |
| 'value' => $currentDate->modify('-' . $thresholdMonths . ' months')->format('Y-m-d H:i:s'), | |
| 'type' => 'DATETIME' | |
| ) | |
| ) | |
| ); | |
| // Retrieve WooCommerce products matching the query | |
| $products = new WP_Query($args); | |
| // Loop through the products and delete them | |
| if ($products->have_posts()) { | |
| while ($products->have_posts()) { | |
| $products->the_post(); | |
| wp_delete_post(get_the_ID(), true); | |
| } | |
| } | |
| // Reset post data | |
| wp_reset_postdata(); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment