首页 > 解决方案 > 无法使用已售罄消息禁用缺货产品变体的功能

问题描述

在我的functions.php 中,我试图在我的产品变体的下拉菜单中添加一条已售罄的消息。例如,如果我的衬衫有小号、中号和大号的款式,而大号的缺货,在下拉菜单中,用户应该会看到大号选项被禁用,并且在“大号”旁边包含一条售罄消息。其他变体应保持活动状态。

我在下面的代码中遇到的问题如下:

如何修复代码以执行我需要它执行的操作?

/**
 * Disable out of stock variations
 * https://github.com/woocommerce/woocommerce/blob/826af31e1e3b6e8e5fc3c1004cc517c5c5ec25b1/includes/class-wc-product-variation.php
 * @return Boolean
 */

// function wcbv_variation_is_active( $active, $variation ) {
//  if( ! $variation->is_in_stock() ) {
//  return false;
//  }
//  return $active;
// }
// add_filter( 'woocommerce_variation_is_active', 'wcbv_variation_is_active', 10, 2 );


add_action( 'woocommerce_variation_is_active', 'woocommerce_sold_out_dropdown' );
function woocommerce_sold_out_dropdown() {
?>
<script type="text/javascript">
jQuery( document ).bind( 'woocommerce_update_variation_values', function() {

jQuery( '.variations select option' ).each( function( index, el ) {
var sold_out = '<?php _e( 'sold out', 'woocommerce' ); ?>';
var re = new RegExp( ' - ' + sold_out + '$' );
el = jQuery( el );

if ( el.is( ':disabled' ) ) {
 if ( ! el.html().match( re ) ) el.html( el.html() + ' - ' + sold_out );
} else {
if ( el.html().match( re ) ) el.html( el.html().replace( re,'' ) );
}
} );
} );
</script>
 <?php
}

标签: javascriptphpjquerywordpresswoocommerce

解决方案


您可以使用此代码(您的代码)获得所需的内容:

// disable options for unavailable variants
add_filter( 'woocommerce_variation_is_active', 'wcbv_variation_is_active', 10, 2 );
function wcbv_variation_is_active( $active, $variation ) {
    if ( ! $variation->is_in_stock() ) {
        return false;
    }
    return $active;
}

现在,要根据股票状态更改每个选项的名称,您可以woocommerce_variation_option_name像这样使用钩子:

add_filter( 'woocommerce_variation_option_name','add_stock_status_after_option_name', 10, 1 );
function add_stock_status_after_option_name( $option ) {
    // only in frontend
    if ( is_admin() ) {
        return $option;
    }
    // get variable product object
    global $product;
    $variation_ids = $product->get_children();
    foreach ( $variation_ids as $variation_id ) {
        $variation = wc_get_product( $variation_id );
        $variation_attributes = $variation->get_variation_attributes();
        foreach ( $variation_attributes as $key => $value ) {
            // slugify option name
            $option_slug = sanitize_title( $option );
            // check if the current option is equal to the variation slug
            if ( $value == $option_slug ) {
                // check if it is out of stock
                if ( ! $variation->is_in_stock() ) {
                    return $option . ' (Out of stock)';
                }
            }
        }
    }
    return $option;
}

该代码已经过测试并且可以正常工作。它需要添加到您的主题的functions.php。


推荐阅读