How to optimize wp_delete_post() function, or why it is so slow
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.
Topic wp-delete-post server Wordpress optimization
Category Web