获取WooCommerce中活跃的所选产品变体的数量

问题描述 投票:1回答:1

我正在网上建立一家商店(使用Woocommerce),展示单品和可变产品。在单个产品页面中,我需要一些输出/文本来依赖单个产品页面中的所选产品是否存货。我正在用PHP构建这个条件。

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

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

我在'woocommerce_before_add_to_cart_button'挂钩。

但是,对于可变产品,我只是不知道如何使其工作。在这种情况下,我需要获得所选/主动变化数量,这必须应对客户端更改页面变化的可能性。

这个问题在BUT之前已经提出,主要针对所有变化,而不是当前/主动变化。

如果有人能说清楚,我将不胜感激。

php jquery wordpress woocommerce variations
1个回答
1
投票

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

你的问题与你想要做的事情并不是很清楚,所以这里有一个自定义函数函数,它挂在woocommerce_before_add_to_cart_button动作钩子中,仅针对可变产品。

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

  • 针对缺货变化显示的自定义消息(也可能是“库存”)
  • 所有活跃的变化库存数量。

jQuery代码检测:

  • 选择了哪种变体(变体ID),
  • 活动选定变体的库存状态

从那里,这段代码能够:

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

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

这是代码示例:

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文件中,或者也可以放在任何插件文件中。

经过测试和工作

使用此代码,您可以获得所有必要的基本代码,以便根据需要自定义内容。

© www.soinside.com 2019 - 2024. All rights reserved.