Skip to content

Instantly share code, notes, and snippets.

@NoahBohme
Created June 23, 2023 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NoahBohme/db975d75f89fefcc9e6d48b88b9bc3eb to your computer and use it in GitHub Desktop.
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
<?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