最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

server - How to optimize wp_delete_post() function, or why it is so slow

programmeradmin0浏览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.

发布评论

评论列表(0)

  1. 暂无评论