Skip to content
Advertisement

Exclude woocommerce tax from multiple product variants based on user role

I need help getting this code to apply to more than one product variant. It works how I need for a single product variant but if I try to change it to include other variants for other products it doesn’t work. I tried array (618, 1380); which are 2 different products and variants. Anyone have any suggestions for how to exclude tax from a number of product variants only for a given user role? I need to exclude tax on retail products for users with a resale license only and charge tax for other products & variants.

add_filter( 'woocommerce_product_get_tax_class', 'change_tax_class_user_role', 10, 2 );
add_filter( 'woocommerce_product_variation_get_tax_class', 'change_tax_class_user_role', 10, 2 );
function change_tax_class_user_role( $tax_class, $product ) {
    $excluded_variation_id = 618;
    $targeted_user_role    = 'ResellerCO';

    if ( $product->is_type('variation') && $product->get_id() == $excluded_variation_id ) {
        return $tax_class;
    } 
    elseif ( current_user_can( $targeted_user_role ) ) {
        return 'Reduced rate';
    }
    return $tax_class;
}

Advertisement

Answer

Hi you should try in_array() for compair multiple variation id

add_filter( 'woocommerce_product_get_tax_class', 'change_tax_class_user_role', 10, 2 );
add_filter( 'woocommerce_product_variation_get_tax_class', 'change_tax_class_user_role', 10, 2 );
function change_tax_class_user_role( $tax_class, $product ) {

   $excluded_variation_id = array (618, 1380);
   $targeted_user_role    = 'ResellerCO';
   $product_id            = $product->get_id();

   if ( $product->is_type('variation') && in_array($product_id, $excluded_variation_id) ) {
       return $tax_class;
   } 
   elseif ( current_user_can( $targeted_user_role ) ) {
       return 'Reduced rate';
   }
   return $tax_class;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement