创建一个 WooCommerce 短代码,该代码将显示单个产品的“购物车中的当前数量”徽章

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

我正在尝试创建一个自定义 WooCommerce 短代码(短代码中带有“产品 id”属性),它将显示客户当前购物车中该特定商品的当前数量。

我有一个良好的开端,我的短代码对于单一/简单产品可以正确显示,但是当涉及到具有多种变体的产品时,就会出现问题。我希望短代码显示父产品的总数;没有必要显示每种变体的数量。

例如,如果客户的购物车有:

  • 产品 - 小号(购物车中 x2)
  • 产品 - 中号(购物车中 x1)
  • 产品 - 大号(购物车中 x3)

我希望简码显示 6。

我认为我可以通过使用

WC()->cart->get_cart()
并确保使用
$cart_item['product_id']
而不是
$cart_item['variation_id']
来做到这一点,但尽管我使用的是“产品 id”并且短代码属性是父产品的 id ,它仅显示最近添加到购物车的任何变体的购物车数量。

关于如何调整它以显示父产品下所有变体的购物车总和,有什么想法吗?

这是我到目前为止的代码:

 if( !function_exists('in_cart_product_quantity') ) {
    function in_cart_product_quantity( $atts ) {

        $atts = shortcode_atts(array('id' => ''), $atts, 'cart_qty_badge');
        if( empty($atts['id'])) return; 

        if ( WC()->cart ) { 
           $qty = 0; 
            foreach (WC()->cart->get_cart() as $cart_item) {
                if($cart_item['product_id'] == $atts['id']) {
                    $qty =  $cart_item['quantity'];
                   
                }
            }
            return $qty;
        }
        return;
    }
    add_shortcode( 'cart_qty_badge', 'in_cart_product_quantity' );
}
php wordpress woocommerce shortcode product-variations
1个回答
0
投票

请改用以下内容,当购物车中的特定可变产品有多种变体时,这应该可以解决您的问题:

if( ! function_exists('get_product_quantity_in_cart') ) {
    function get_product_quantity_in_cart( $atts ) {
        // Extract shortcode attributes
        extract( shortcode_atts( array(
            'id' => '',
        ), $atts, 'cart_qty_badge' ) );
        
        if( empty($id) || WC()->cart->is_empty() ) return; 

        $total_qty = 0; 
        
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if( $cart_item['product_id'] == $id ) {
                $total_qty += $cart_item['quantity'];
            }
        }
        return $total_qty > 0 ? $total_qty : '';
    }
    add_shortcode( 'cart_qty_badge', 'get_product_quantity_in_cart' );
}

应该可以。

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