根据用户角色和产品类别应用不同的税(Woocommerce)

2023-12-26

如果用户具有特定角色,但仅限于某些产品类别,我需要应用不同的税。

示例:如果具有“Vip”角色的客户 A 购买“Bravo”或“Charlie”类别的商品,则适用的税费将为 4%,而不是 22%

这是我写的代码,另一部分是在谷歌上找到的,但我不明白我错在哪里。

请问有人可以帮助我吗?

function wc_diff_rate_for_user( $tax_class, $product ) {
  global $woocommerce;

    $lundi_in_cart = false;

    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];
        $terms = get_the_terms( $_product->id, 'product_cat' );

            foreach ($terms as $term) {
                $_categoryid = $term->term_id;
            }
                if (( $_categoryid === 81 ) || ( $_categoryid === 82 ) )) {

                    if ( is_user_logged_in() && current_user_can( 'VIP' ) ) {
                        $tax_class = 'Reduced Rate';
                    }
                }   
    }

  return $tax_class;
}

税费是按购物车中的每行商品计算的。您不必循环购物车商品。相反,请检查当前项目是否具有您要查找的类别。

尝试这样...

add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
function wc_diff_rate_for_user( $tax_class, $product ) {

    // not logged in users are not VIP, let's move on...
    if (!is_user_logged_in()) {return $tax_class;}

    // this user is not VIP, let's move on...
    if (!current_user_can( 'VIP' ) ) {return $tax_class;}

    // it's already Reduced Rate, let's move on..
    if ($tax_class == 'Reduced Rate') {return $tax_class;}

    // let's get all the product category for this product...
    $terms = get_the_terms( $product->id, 'product_cat' );
    foreach ( $terms as $term ) { // checking each category 
        // if it's one of the category we'er looking for
        if(in_array($term->term_id, array(81,82))) {
            $tax_class = 'Reduced Rate';
            // found it... no need to check other $term
            break;
        }
    }

    return $tax_class;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据用户角色和产品类别应用不同的税(Woocommerce) 的相关文章