我编写了一个遍历所有产品的函数,查找缺货的变体,然后删除该变体和与变量产品相关联的属性,以便所有产品过滤器插件在缺货时都不会显示特定的变体
我的功能在我的测试站点上运行良好,但是我正在寻找一些建议,以使其更高效,因为我担心要在具有数百种产品的实时站点上运行它,每个产品有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()
仅返回变量乘积,并且可以对我的代码进行效率/性能方面的改进吗?
谢谢!
答案 0 :(得分:1)
通过WC_Product_Query
when using wc_get_products()
,您可以使用“ type
”参数来仅定位变量产品,例如:
$products = wc_get_products( array( 'status' => 'publish', 'limit' => -1, 'type' => 'variable' ) );
这将提高代码的效率/性能。
注意:$atts
变量应在第二个foreach循环之后初始化,例如:$atts = array();