计算 WooCommerce 购物车中的自定义分类术语并将购物车总数乘以数量
Count custom taxonomy terms in WooCommerce cart and multiply the cart total by the number
我有一个 WooCommerce 产品的自定义分类法,假设 slug 是 city
。
代码的目标是遍历购物车内容,并保存唯一 city 分类条目的数量。
之后,原始价格需要乘以统计的所有唯一城市个分类法的数量。
我设法找到了这段代码,它获得了分类术语,但忘记了下一步该做什么:
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$term_names = wp_get_post_terms( $product_id, 'city', array('fields' => 'names') );}
如有任何建议,我们将不胜感激!
要更改购物车总数,您可以使用 woocommerce_calculated_total
过滤器挂钩
然后可以使用count(),它计算数组$term_names
中的所有元素并将结果添加到$counter
变量
所以你得到:
function filter_woocommerce_calculated_total( $total, $cart ) {
// Initialize
$counter = 0;
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Product ID in cart
$product_id = $cart_item['product_id'];
// Get terms
$term_names = wp_get_post_terms( $product_id, 'city', array( 'fields' => 'names' ) );
// Add to counter
$counter += count( $term_names );
}
return $total * $counter;
}
add_filter( 'woocommerce_calculated_total', 'filter_woocommerce_calculated_total', 10, 2 );