将“缺货”类添加到显示为样本的变体 - WooCommerce

问题描述 投票:0回答:2

我试图想办法在WooCommerce变量中添加一个“缺货”类,当它们的库存水平为0时显示为样本。

当我们在标准的WooCommerce下拉列表中显示时,我发现了多种“灰化”缺货变化的方法 - 代码如下所示:

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

但是,当使用插件将我的变体显示为样本时,这不起作用。

我目前有一个size属性,并使用插件将每个大小显示为可以选择的单独框。与此主题中显示的内容类似:Click Here

是否有一些PHP或JS可用于将新库存添加到缺货变量中,这将允许我更改CSS。将它们显示为红色框,例如穿过它。

在我搜索到目前为止,我空手而归,所以任何帮助将不胜感激。

php jquery wordpress woocommerce
2个回答
0
投票

好的,我为插件WooCommerce Variation Swatches and Photos编写了这段代码。我们将做的是为零库存的任何变化添加一个称为缺货的类。您需要确保已选中“管理库存”来设置变体。当变体的库存为零时,该类将添加到变体链接中。然后,您可以设置类的样式,但是要显示它已禁用。

add_filter('woocommerce_swatches_get_swatch_anchor_css_class', 'add_swatch_out_stock_class', 10, 2);

function add_swatch_out_stock_class( $anchor_classes, $swatch_term ) {
    if ( is_product() ) {
        global $post;
        $product = wc_get_product($post);

        if ( $product->get_type() === 'variable' ) {
            foreach( $product->get_available_variations() as $variation ) {
                $product_variation = new WC_Product_Variation($variation['variation_id']);

                if( $product_variation->get_stock_quantity() === 0 ) {
                    foreach( $product_variation->get_variation_attributes() as $var_attribute) {
                        if( $swatch_term->term_slug === $var_attribute) {
                            $anchor_classes .= ' out-of-stock';
                        }
                    }
                }
            }
        }
    }
    return $anchor_classes;
}

要显示样本内的大小标签,可以使用此过滤器删除text-index属性。

add_filter('woocommerce_swatches_picker_html', 'remove_text_indent', 10, 2);

function remove_text_indent( $picker, $swatch_term) {

    return str_replace('text-indent:-9999px;', '', $picker);
}

0
投票

如果您需要隐藏颜色样本(仅限颜色选项),则可以在标记之前使用此标记。 NB!您必须检查插件样本的类是否相同您使用的示例更改.tawcvs-swatches为您的样式类插件使用的内容。

<script language="JavaScript" type="text/javascript" src="jquery/jquery.js"></script>
<script>
    jQuery.noConflict();
    (function ($) {
        function readyFn() {
            $( ".variations_form" ).on( "woocommerce_update_variation_values", function () {
            let $swatches = $('.tawcvs-swatches');
            $swatches.find('.swatch').removeClass('hidden');
            $swatches.each(function(){
                let $select = $(this).prev().find('select');
                $(this).find('.swatch').each(function(){
                    if (!($select.find('option[value="'+ $(this).attr('data-value') +'"]').length > 0)) {
                        $(this).addClass('hidden');
                    }
                })
            })
        } );
        }

        $(document).ready(readyFn); 
    })(jQuery);

</script>
© www.soinside.com 2019 - 2024. All rights reserved.