显示“缺货"具有多种变体的 Woocommerce 产品变体旁边的文本 [英] Showing "Out of Stock" text next to variation in Woocommerce product with multuiple variations

查看:19
本文介绍了显示“缺货"具有多种变体的 Woocommerce 产品变体旁边的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处寻找,但似乎无法找到解决非常简单问题的方法.我有一个 Woocommerce 商店,我想向用户显示一条消息缺货";如果缺货,请在变体旁边.我不希望它变灰,我希望用户能够选择它,以便他们可以根据需要查看价格.我在网上找到的大多数片段仅在它们的产品有一个变体时才有效,但我需要它至少对两个变体有效.我的网站销售移动设备,例如:

如果用户选择存储为 64GB,则颜色列表会更新,显示 64GB 中哪些颜色缺货.如果所有颜色都缺货,那么在 64GB 旁边会显示缺货";还有.

如果先选择颜色,则存储 - 颜色列表会根据缺货内容进行更新.

有人可以帮我吗?试图让这个工作变得疯狂.下面的代码可以按照我上面提到的确切方式(它适用于多种产品)使缺货产品变灰,但我不知道如何针对上面提到的用例修改它.

add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );函数grey_out_variations_when_out_of_stock( $grey_out, $variation ){如果 ( ! $variation->is_in_stock() ){返回假;}别的{打印_r($option_class);返回 $term_name .' - 缺货';;}}

解决方案

您可以检查产品变体的可用性只有在选择了除一个属性以外的所有属性,而不是之前.>

所有必要的数据都显示在产品页面上,因此您可以使用 jQuery 脚本来处理它.

在变体表单中有 data-product_variations 属性,它包含一个数组,其中包含产品变体的所有详细信息(变体 ID、库存状态、它使用的属性等...).

然后,您可以在所选属性和可能的​​产品变体之间进行比较.

想法是这样的:

  1. 检查产品页面上是否有多个属性(下拉菜单)
  2. 如果除了一个属性之外的所有属性(下拉列表)都被选中,获取属性slug和所选选项的属性值
  3. 将它们与每个变体使用的属性进行比较,如果所选属性相同,则获取要选择的最后一个属性的库存状态
  4. 向产品变体没有库存的每个选项添加文本缺货".为此,它将使用 woocommerce_update_variation_values 事件,该事件在通过 Ajax 更新选项后触发(否则更改将被覆盖)

<块引用>

以下代码适用于 2 个或更多属性(下拉列表)可变产品页面.

//添加文字缺货";到最后一个未选择的属性下拉列表的每个选项add_action('wp_footer', 'add_out_of_stock_text_to_the_last_unselected_attribute_dropdown');函数 add_out_of_stock_text_to_the_last_unselected_attribute_dropdown() {?><script type="text/javascript">//初始化一个全局变量,该变量将包含要更新的属性值(缺货")让 globalAttributesToUpdate;jQuery(函数($){//检查是否只有一个属性没有被选中函数 isLastAttribute(){//如果只有一个下拉菜单,则返回 falseif ( $('form.variations_form select').length == 1 ) {返回假;}//计算所有选定的属性(不包括选择一个选项")让计数 = 0;$('form.variations_form select').each(function(){if ( $(this).find(':selected').val() ) {计数++;}});//如果尚未选择属性,则返回 trueif ( $('form.variations_form select').length - count == 1 ) {返回真;} 别的 {返回假;}}$('form.variations_form select').change(function() {如果 ( isLastAttribute() ) {//每次都清除全局变量globalAttributesToUpdate = [];让 attrToFind = {};//包含一个带有 slug 和所选属性值的对象让 attrToSet;//包含尚未选择的属性的 slug$('form.variations_form select').each(function(index,object){if ( $(this).find(":selected").val() ) {attrToFind[$(this).data('attribute_name')] = $(this).find(":selected").val();} 别的 {attrToSet = $(this).data('attribute_name');}});//获取data-product_variations"的值;变体形式的属性让variationData = $('form.variations_form').data(product_variations");$(variationData).each(function(index,object) {让 attrVariation = object.attributes;让 attrVariationLenght = Object.keys(attrVariation).length;让发现= 0;让设置;让 valueToSet;//检查所有可能的属性组合(对于单个变体)//基于选择的属性$.each( attrVariation, function( attr, value ) {if ( attrToFind && attrToFind[attr] == value 中的 attr ) {发现++;} 别的 {//如果变体缺货,它会获取 slug 和 value 以添加文本缺货";如果( object.is_in_stock == false ){toSet = attr;valueToSet = 值;}}});//如果只有一个属性缺失if ( attrVariationLenght - 发现 == 1 ) {if ( toSet == attrToSet ) {让 obj = {};obj[toSet] = valueToSet;globalAttributesToUpdate.push(obj);}}});}});//插入文本缺货";更新变体后//基于globalAttributesToUpdate";全局变量$('body').on('woocommerce_update_variation_values', function(){if ( globalAttributesToUpdate !== undefined && globalAttributesToUpdate.length ) {$.each( globalAttributesToUpdate, function( key, attribute ) {$.each( 属性,函数( attrName, attrValue ) {$('select[name='+attrName+'] > option[value="'+attrValue+'"]').append( "(缺货)");});});}});});<?php}

代码已经过测试并且可以工作.将它添加到您的活动主题的functions.php.

结果

相关答案

I have been looking EVERYWHERE and I cannot seem to find a solution to a very simple problem. I have a Woocommerce store and I want to show to the user a message "Out of stock" next to the variation if it is out of stock. I do not want it grayed out, I want the user to be able to select it so they can view the price if they wish. Most snippets I find online only works when they product has ONE variation but I need it to work for at least two. My website sells mobile devices so for example:

If a user selects the storage as 64GB then the color list updates showing which colors are out of stock in 64GB. If all colors are out of stock then next to 64GB it shows "Out of stock" also.

If the color is selected first, then the storage - the color list is then updated with what is out of stock.

Can anyone help me out here? Going insane trying to get this working. The below code works to gray out out of stock products in the exact way I mentioned above (it works for multiple products) but I can't figure out how to modify it for the use case mentioned above.

add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
function grey_out_variations_when_out_of_stock( $grey_out, $variation ){
if ( ! $variation->is_in_stock() ){
  return false;
 }else{
print_r($option_class);
  return $term_name . ' - Out of Stock';;
 }
}

解决方案

You can check the availability of a product variation only if all but one of the attributes have been selected, not before.

All the necessary data is present on the product page and therefore you can use a jQuery script to process it.

In the variation form there is the data-product_variations attribute which contains an array with all the details of the product variations (variation id, stock status, attributes it uses, etc ...).

You can then make a comparison between the selected attributes and possible product variations.

The idea is this:

  1. Check that there is more than one attribute (dropdown) on the product page
  2. If all attributes (dropdowns) have been selected except one, get the attribute slug and the attribute value of the selected options
  3. It compares them with the attributes that each single variation uses and, if the selected attributes are the same, gets the stock status of the last attribute to be selected
  4. Adds the text "Out of stock" to each option whose product variation is not in stock. To do this it will use the woocommerce_update_variation_values event which fires after updating the options via Ajax (otherwise the changes will be overwritten)

The following code will work for 2 or more attributes (dropdowns) in the variable product page.

// add the text "Out of stock" to each option of the last unselected attribute dropdown
add_action( 'wp_footer', 'add_out_of_stock_text_to_the_last_unselected_attribute_dropdown' );
function add_out_of_stock_text_to_the_last_unselected_attribute_dropdown() {

    ?>
    <script type="text/javascript">

    // initializes a global variable that will contain the attribute values to be updated ("Out of stock")
    let globalAttributesToUpdate;

    jQuery(function($){

        // check if only one attribute is missing to be selected
        function isLastAttribute(){
            // if there is only one dropdown it returns false
            if ( $('form.variations_form select').length == 1 ) {
                return false;
            }
            // counts all selected attributes (excluding "Choose an option")
            let count = 0;
            $('form.variations_form select').each(function(){
                if ( $(this).find(':selected').val() ) {
                    count++;
                }
            });
            // if an attribute has not yet been selected, it returns true
            if ( $('form.variations_form select').length - count == 1 ) {
                return true;
            } else {
                return false;
            }
        }

        $('form.variations_form select').change(function() {
            if ( isLastAttribute() ) {
                // clear the global variable every time
                globalAttributesToUpdate = [];
                let attrToFind = {}; // contains an object with slug and value of the selected attributes
                let attrToSet; // contains the slug of the attribute not yet selected
                $('form.variations_form select').each(function(index,object){
                    if ( $(this).find(":selected").val() ) {
                        attrToFind[$(this).data('attribute_name')] = $(this).find(":selected").val();
                    } else {
                        attrToSet = $(this).data('attribute_name');
                    }
                });
                // gets the value of the "data-product_variations" attribute of the variations form
                let variationData = $('form.variations_form').data("product_variations");
                $(variationData).each(function(index,object) {
                    let attrVariation = object.attributes;
                    let attrVariationLenght = Object.keys(attrVariation).length;
                    let found = 0;
                    let toSet;
                    let valueToSet;
                    // check all possible combinations of attributes (for single variation)
                    // based on the selected attributes
                    $.each( attrVariation, function( attr, value ) {
                        if ( attr in attrToFind && attrToFind[attr] == value ) {
                            found++;
                        } else {
                            // if the variation is out of stock it gets slug and value to add the text "Out of stock"
                            if ( object.is_in_stock == false ) {
                                toSet = attr;
                                valueToSet = value;
                            }
                        }
                    });
                    // if only one attribute is missing
                    if ( attrVariationLenght - found == 1 ) {
                        if ( toSet == attrToSet ) {
                            let obj = {};
                            obj[toSet] = valueToSet;
                            globalAttributesToUpdate.push(obj);
                        }
                    }
                });
            }
        });

        // inserts the text "Out of stock" after updating the variations
        // based on the "globalAttributesToUpdate" global variable
        $('body').on('woocommerce_update_variation_values', function(){
            if ( globalAttributesToUpdate !== undefined && globalAttributesToUpdate.length ) {
                $.each( globalAttributesToUpdate, function( key, attribute ) {
                    $.each( attribute, function( attrName, attrValue ) {
                        $('select[name='+attrName+'] > option[value="'+attrValue+'"]').append( " (Out of stock)" );
                    });
                });
            }
        });
    });
    </script>
    <?php

}

The code has been tested and works. Add it to your active theme's functions.php.

RESULT

RELATED ANSWERS

这篇关于显示“缺货"具有多种变体的 Woocommerce 产品变体旁边的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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