获取 WooCommerce 中活动的选定产品变体的数量

Get quantity of the active selected product variation in WooCommerce

我正在(使用 Woocommerce)建立一个在线商店,它将展示单一和可变的产品。在单品页面中,我需要一些 output/text 来取决于单品页面中所选的产品是否有货。我正在 PHP 中构建此条件。

对于单个产品,这是微不足道的:

$qty = $product->get_stock_quantity();
if ( ( ... ) and ( $qty > 0 ) ) {
    ...
}

我正在挂机'woocommerce_before_add_to_cart_button'

但是,对于可变产品,我只是不知道如何让它发挥作用。在这种情况下,我需要获取 selected/active 变体数量,这必须应对客户端更改页面变体的可能性。

这个问题之前已经提出过,但主要是针对所有变体而不是 current/active 那个。

如果有人能提供一些帮助,我将不胜感激。

获取所选变体库存数量的唯一方法是使用 jQuery/Javascript,因为它主要是客户端(而非服务器端)的实时事件。

你的问题与你想做什么并不清楚,所以这里有一个自定义函数挂钩在 woocommerce_before_add_to_cart_button 动作挂钩中,仅针对变量产品。

在该函数中,我将一些数据从 php 传递到 javascript,例如:

  • 为缺货变体显示的自定义消息 (它也可能用于 "In stock")
  • 所有活跃变体库存数量。

jQuery代码检测:

  • 选择了哪个变体(变体 ID),
  • 有效所选变体的库存状态

从那里开始,此代码能够:

  • 获取所选变体的库存数量(我不知道你想用它做什么)
  • 当所选变体缺货时显示自定义消息。

在 jQuery 代码中有一个函数将 return 所选变体的库存数量。

这是这个代码示例:

add_action( 'woocommerce_before_add_to_cart_button', 'get_selected_variation_stock', 11, 0 );
function get_selected_variation_stock() {
    global $product, $wpdb;

    // HERE set your custom message
    $message_outofstock = __('My custom "out of stock" message');

    // Get the visible product variations stock quantity
    $variations_data = array();
    $child_ids = $product->get_visible_children();
    $child_ids = implode( ',',$child_ids );
    $results = $wpdb->get_results( "
        SELECT p.ID, pm.meta_value as stock_qty
        FROM {$wpdb->prefix}posts as p
        INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
        WHERE p.post_type LIKE 'product_variation'
        AND p.ID IN ($child_ids) AND pm.meta_key LIKE '_stock'
    " );

    foreach( $results as $result ){
        // Set in an indexed array for each variation ID the corresponding stock qty
        $variations_data[$result->ID] = $result->stock_qty;
    }

    ?>
    <script>
    jQuery(document).ready(function($) {
        var vData = <?php echo json_encode($variations_data); ?>,
            stock = '.woocommerce-variation-availability > .stock';

        // Function that get the selected variation stock quantity and returns it
        function getTheStockQty( a=vData ){
            $.each( a, function( index, value ){
                if( index == $('input.variation_id').val() )
                    return value;
            });
        }

        // Once loaded (if a variation is selected by default)
        setTimeout(function(){
            var stockQty = getTheStockQty();
            if( 0 < $('input.variation_id').val() && $(stock).hasClass('out-of-stock')){ // OUT OF STOCK
                // Output a custom message for "out of stock"
                $(stock).text('<?php echo $message_outofstock; ?>');
                // Testing output in the browser JS console
                console.log('(1)'+$(stock).html()+' | Stock qty: '+stockQty);
            } else if( 0 < $('input.variation_id').val() ) { // IN STOCK
                // Testing output in the browser JS console
                console.log('(2)'+$(stock).html()+' | Stock qty: '+stockQty);
            }
        }, 300);

        // On live selected variation
        $('select').blur( function(){
            var stockQty = getTheStockQty();
            if( 0 < $('input.variation_id').val() && $(stock).hasClass('out-of-stock')){ // OUT OF STOCK
                // Output a custom message for "out of stock"
                $(stock).text('<?php echo $message_outofstock; ?>');
                // Testing output in the browser JS console
                console.log('(1 live)'+$(stock).html()+' | Stock qty: '+stockQty);
            } else if( 0 < $('input.variation_id').val() ) { // IN STOCK
                // Testing output in the browser JS console
                console.log('(2 live)'+$(stock).html()+' | Stock qty: '+stockQty);
            }
        });
    });
    </script>
    <?php
}

此代码位于您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

已测试并有效

With this code, you get all the necessary base code to customize things just like you want.