Andres Molina Perez-Tome Andres Molina Perez-Tome - 8 months ago 46
PHP Question

Tax class "Zero rate" per user role on specific product ID's

I got this code that will apply tax free on a user role regardless of what they order, which is fine.

But now I need another user role that will apply tax free on specific products id, and I'm not sure how to acomplish that.

The code im using right now for tax free on all products for specific user role is:

// Apply a different tax rate based on the user role.

function wc_diff_rate_for_user( $tax_class, $product ) {
// Getting the current user
$current_user = wp_get_current_user();
$current_user_data = get_userdata($current_user->ID);

if ( in_array( 'administrator', $current_user_data->roles ) || in_array( 'userrolename', $current_user_data->roles ) )
$tax_class = 'Zero Rate';

return $tax_class;
add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
// Fin Apply a different tax rate based on the user role.

Answer Source

Here is the code that will apply this "Zero Rate" tax class for some defined products and some defined user roles:

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

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )

    // Define HERE your targeted products IDs
    $products_ids_arr = array(12 ,15, 24);

    // Define HERE your targeted user roles
    $users_role_arr = array('administrator', 'userrolename');

    //Getting the current user data
    $user_data = get_userdata(get_current_user_id());

    foreach ($users_role_arr as $user_role)
        if ( in_array( $user_role, $user_data->roles ) && in_array( $cart_item->id, $products_ids_arr ) ) {
            $tax_class = 'Zero Rate';

    return $tax_class;


This code is tested and works.

Code goes in any php file of your active child theme (or theme) or also in any plugin php files.