Apply different taxes based on user role and product category (Woocommerce)

I need a different tax if the user has a specific role, but only in certificate categories.

Example: if client A with the VIP role buys a Bravo or Charlie product, the applicable tax will be 4% instead of 22%

This code partially wrote me another piece made by google, but I don’t understand where I am going wrong.

Please can someone help me?

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;
}
+4
source share
1 answer

. . , , .

...

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 move on...
    if (!is_user_logged_in()) {return $tax_class;}

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

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

    // let 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 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;
}
+1

Source: https://habr.com/ru/post/1626126/


All Articles