通过变体改进 WC_Product_Query Woocommerce 产品

Improve WC_Product_Query on Woocommerce products with variations

我编写了一个函数来遍历所有产品,找到缺货的变体,然后删除变体和变量产品相关属性,这样任何产品过滤器插件在缺货时都不会显示特定的变体库存。

我的功能在我的测试网站上运行良好,但我正在寻找一些建议来提高它的效率,因为我对 运行 它在一个有数百种产品的实时网站上有一些担忧,大约有 15每个产品的变化。

这是我的函数代码:

function wpmad_purge_variations_not_in_stock(){

    echo 'Purging products...<br><br>';

    $args = array( 'status' => 'publish', 'limit' => -1 );
    $products = wc_get_products( $args );

    foreach ( $products as $product ){

        if ( $product->is_type( 'variable' ) ){

            $product_id = $product->id;
            // Get all available product variations for current product/item
            $variations = $product->get_available_variations();

            // Loop through each of the available variations
            foreach ( $variations as $variation ){

                // Check if variation is no longer in stock
                if ( $variation['is_in_stock'] == '' ){

                    $variation_id = $variation['variation_id'];

                    // Attribute counter
                    $count = 1;

                    // For each variation attribute
                    foreach ( $variation['attributes'] as $att_name => $att_value ){

                        $atts[$count]['name'] = str_replace( 'attribute_', '', $att_name );
                        $atts[$count]['value'] = $att_value;

                        $count++; // Increase counter for each loop

                    }

                    // Delete product variation post
                    echo 'Deleted product variation ID #' . $variation_id . '<br>';
                    wp_delete_post( $variation_id, true );

                    // For each attribute
                    foreach ( $atts as $att ){
                        // Remove attribute from main product
                        echo 'Deleted product attribute (' . $att['name'] . ' - ' . $att['value'] . ') for product ID #' . $product_id . '<br><br>';
                        wp_remove_object_terms( $product_id, $att['value'], $att['name'] );
                    }

                }

            }

        }
    }

    echo 'Product variations have now been purged if out of stock';

}

是否可以将函数 wc_get_products() 仅用于 return 可变产品,是否可以对我的代码进行任何 efficiency/peformance 改进?

提前致谢!

通过 WC_Product_Query when using wc_get_products(),您可以使用“type”参数来仅定位变量产品,例如:

$products = wc_get_products( array( 'status' => 'publish', 'limit' => -1, 'type' => 'variable' ) );

这将提高代码的效率/性能。

注意: $atts 变量应该在第二个 foreach 循环之后立即初始化,例如:$atts = array();