加快Woocommerce批量可变产品的创建

时间:2019-01-15 13:10:06

标签: wordpress woocommerce

我正在创建可变产品。例如,我有9种颜色,9种尺寸。 1个产品的总变化量为9×9 = 81。

Foreach版本,下面是运行的功能。

function create_product_variation( $product_id, $variation_data, $productColorsAndIDs ){
    // Get the Variable product object (parent)
    $product = wc_get_product($product_id);
    $variation_post = array(
        'post_title'  => $product->get_title(),
        'post_name'   => 'product-'.$product_id.'-variation',
        'post_status' => 'publish',
        'post_parent' => $product_id,
        'post_type'   => 'product_variation',
        'guid'        => $product->get_permalink()
    );

    // Creating the product variation
    $variation_id = wp_insert_post( $variation_post );

    // Get an instance of the WC_Product_Variation object
    $variation = new WC_Product_Variation( $variation_id );

    // Iterating through the variations attributes
    foreach ($variation_data['attributes'] as $attribute => $term_name )
    {
        //Only have 2 attributes, size and color.
        $taxonomy = 'pa_'.$attribute;
        update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_name );
    }

    // Prices
    $variation->set_price( $variation_data['regular_price'] );
    $variation->set_regular_price( $variation_data['regular_price'] );
    $variation->set_image_id($variation_data['variation_thumbnail_id']);

    $variation->save(); // Save the data
}

在运行上面的代码之前,我将循环封装如下:

wp_defer_term_counting( false);     //Speeding Up Bulk Update Tricks
wp_defer_comment_counting( false );  //Speeding Up Bulk Update Tricks

//Here comes the loop, which calls the above function create_product_variation().

wp_defer_term_counting( true );     
wp_defer_comment_counting( true ); 

即使我使用快速托管(SiteGround GoGeek托管计划),创建过程也很慢。上面的代码在1-2分钟内创建了1个产品,这相当慢,而且在大多数情况下,我会收到网关504错误,而运行它。

我在这里想念什么?如何优化它以更快地工作?

0 个答案:

没有答案