Skip to content

Instantly share code, notes, and snippets.

@NoahBohme
Created June 23, 2023 15:50
Show Gist options
  • Save NoahBohme/db975d75f89fefcc9e6d48b88b9bc3eb to your computer and use it in GitHub Desktop.
Save NoahBohme/db975d75f89fefcc9e6d48b88b9bc3eb to your computer and use it in GitHub Desktop.

Revisions

  1. NoahBohme created this gist Jun 23, 2023.
    34 changes: 34 additions & 0 deletions remove-3-month-woo-wp.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    <?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();