我想为类别 (A) 添加费用,但仅当订单中有其他类别(B、C、D 等)的产品时才计算。
但如果仅订购 A 类产品,则不适用该税。
在我的代码中,这两种情况都会添加费用。您能指导我找到更好的解决方案吗?
我在我的网站上添加此代码:
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
$categories = array('396');
$fee_amount = 0;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
$fee_amount = 20;
}
// Adding the fee
if ( $fee_amount > 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Taxa livrare ROPET", "woocommerce" ), $fee_amount, false );
}
}
您可以使用wp_get_post_terms()
检索帖子的术语。在浏览购物车内容时,我们收集术语 ID,
然后我们可以比较它是否存在匹配。
WordPress使用的功能:
-
wp_get_post_terms() https://developer.wordpress.org/reference/functions/wp_get_post_terms/- 检索帖子的条款
使用的 PHP 函数:
-
in_array() https://www.php.net/manual/en/function.in-array.php- 检查数组中是否存在某个值
-
数组相交() https://www.php.net/manual/en/function.array-intersect.php- 计算数组的交集
所以你得到:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only use term IDs
$category_a = 15;
$other_categories = array( 16, 17, 18 );
// Fee amount
$fee_amount = 20;
// Initialize
$term_ids = array();
// Loop through cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Retrieves the terms for a post.
$terms = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
// Loop through
foreach ( $terms as $term_id ) {
// Checks if a value NOT exists in an array
if ( ! in_array( $term_id, $term_ids ) ) {
// Push
$term_ids[] = $term_id;
}
}
}
// Check for a specific category (A)
if ( in_array( $category_a, $term_ids ) ) {
// Check if ANY of the term ids exist
if ( ! empty ( array_intersect( $other_categories, $term_ids ) ) ) {
// Last argument is related to enable tax (true or false)
$cart->add_fee( __( 'Taxa livrare ROPET', 'woocommerce' ), $fee_amount, false );
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)