Display variation stock status on single dropdown variable products in Wocommerce 3 [closed]

为君一笑 提交于 2020-12-13 03:17:13

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/65002729/display-variation-stock-status-on-single-dropdown-variable-products-in-wocommerc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!