1

在 WooCommerce 可变产品答案代码中的每个属性值旁边使用显示库存状态来显示可变产品页面的单个产品属性下拉列表中的变体库存状态。

这工作正常,但需要太多时间来加载产品。

如何优化代码以使其加载更快?

4

1 回答 1

1

请改用以下内容,这会更轻一些(因此可变产品应快速加载)

add_filter( 'woocommerce_variation_option_name', 'customizing_variations_terms_name' );
function customizing_variations_terms_name( $term_name ){
    global $product;

    if( is_admin() ) return $term_name; // Only on frontend single products

    // Iterating through each visible product variation Ids
    foreach( $product->get_visible_children() as $variation_id ){
        $variation = new WC_Product_Variation( $variation_id );

        $stock_status = $variation->get_stock_status();
        $stock_qty    = $variation->get_stock_quantity();

            // The attributes taxonomy key and slug value for this variation
            $attributes = $variation->get_attributes();

        // Caution: Works only for 1 attribute set in the product
        if(count($attributes) == 1 ) {
            $attributes_keys = array_keys($attributes);
            $attr_taxonomy   = str_replace('attribute_', '', reset($attributes_keys) );
            if( $variation->get_attribute( $attr_taxonomy ) === $term_name ) {
                break; // stop the loop
            }
        }
        $term_name .= ' - ' . $stock_status;
        $term_name  = $stock_qty > 0 ? $term_name . ' ('.$stock_qty.')' : $term_name;
    }
    return $term_name;
}
于 2020-11-25T15:37:06.103 回答