繁体   English   中英

向显示为色板的变体添加“缺货”类 - WooCommerce

[英]Adding an “out-of-stock” class to variations shown as swatches - WooCommerce

我试图找出在 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;
}

但是,当使用插件将我的变化显示为色板时,这不起作用。

我目前有一个尺寸属性,并使用一个插件将每个尺寸显示为一个可以选择的单独框。 类似于此线程中显示的内容: 单击此处

是否有一些 PHP 或 JS 可以用来将新库存添加到缺货变体中,然后我可以更改 CSS。 将它们显示为一个红色框,例如带有一个十字。

到目前为止,在我的搜索过程中,我空手而归,因此将不胜感激。

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

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

如果您需要隐藏色板(仅限颜色选项),那么您可以使用这个放置在标签之前。 注意! 您必须检查插件色板的类是否相同,您使用的示例更改 .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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM