0

I have a code block to delete all the products from a store. This products have several custom fields and some images attached. The code is below:

set_time_limit(0);

define('WP_USE_THEMES', false);
require_once("../../wp-load.php");

$query = new WP_Query(array(
    'ignore_sticky_posts' => true,
    'no_found_rows'       => true,
    'post_type'           => array( 'product' ),
    'post_status'         => array( 'publish' ),
    'posts_per_page'      => -1,
    'fields'              => 'ids'
));

foreach ($query->posts as $ID) {
    $media = get_attached_media('', $ID);
    foreach ($media as $image) {
        wp_delete_attachment($image->ID, true);
    }
    wp_delete_post($ID, true);
}

The problem is that it is taking too long to execute the script. It deletes a product each second or more. I have 30K+ products. The initial query is really fast retrieving all the IDs the problem is the foreach loop.

How could I speed it up? My hosting has 1GB of RAM and 2 Cores, SSD. PHP 7.3. I did some tests in local environment and it was way faster, taking few seconds to eliminate all the products.

4
  • 1
    Deleting posts is not a simple process. Not only does the row need to be deleted, but so do any taxonomy terms or post meta attached to the product. WooCommerce also needs to delete associated data from its lookup table. Not to mention that any functions hooked to run on post deletion also need to run. It's not reasonable to expect deleting 30k WordPress posts properly to happen quickly. Feb 14 '20 at 16:01
  • i disagree. its not complicated for sql to delete lots of data. WordPress writes the function in a way that works well for deleting one post at a time. For starters look into defer term counting. otherwise you can write custom sql if you know what your doing. its obviously more risky and will take many steps to remove all stale data but for sure you can accomplish the same result faster, not including time spent coding.
    – Joel M
    Feb 14 '20 at 16:21
  • 1
    If you write your own sql be careful not to delete all product data without marking the products images used. you'll have a very hard time knowing which images used to belong to products that now don't exist
    – Joel M
    Feb 14 '20 at 16:24
  • 1
    some plugins can easily clean orphaned post meta and term data. they can make your life easier if you only delete from the posts table. these 3 things can clean up most data but certainly not all, ie image files. term counts will need to be regenerated. there could be other things. don't assume that custom deletion guarantees the same resulting state. it def can but lots of things to consider
    – Joel M
    Feb 14 '20 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.