在 Wocommerce 3 中显示单个下拉变量产品的变化库存状态 [英] Display variation stock status on single dropdown variable products in Wocommerce 3

查看:27
本文介绍了在 Wocommerce 3 中显示单个下拉变量产品的变化库存状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Show stock status next to each attribute value in WooCommerce variable products answer code to display the variation stock status on single product attribute dropdown for variable product pages.

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

This works fine, but take too much time to load a product.

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

How could I optimize the code to make it load faster?

推荐答案

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

Use the following instead, that will be a bit lighter (so variable products should load quickly):

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;
}

这篇关于在 Wocommerce 3 中显示单个下拉变量产品的变化库存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆