我正在try 创建一个自定义的WooCommerce短码(在短码中有一个‘产品id’属性),它将显示客户当前在其购物车中拥有的该特定项目的当前数量.
我有一个很好的开始,我的短码对于单一/简单的产品可以正确显示,但当涉及到具有多种变体的产品时,就会有一个问题.我想用短码来显示母公司产品的总数;没有必要显示每个变种的数量.
例如,如果客户的购物车具有:
- 产品-小型(购物车中的x2)
- 产品-中等(购物车中的x1)
- 产品-大型(购物车中的x3)
我希望短码显示为6.
我想我可以通过使用WC()->cart->get_cart()
并确保使用$cart_item['product_id']
而不是$cart_item['variation_id']
来做到这一点,但尽管我使用了'product id'并且shortcode属性是父产品的id,但它只显示最近添加到购物车中的任何变化的购物车数量.
你有什么 idea ,我可以调整它,以显示所有变化下的父产品的购物车总和?
以下是我到目前为止拥有的代码:
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' );
}