phpwordpresswoocommerceuser-roles

WooCommerce - Enabling "Zero rate" tax class to some specific user roles


In wy WooCommerce web site, I'm going to be selling to distributors AND resellers. The problem is that resellers are exempt from TAXES and therefore I need with a custom function to enable Zero taxe rate for certain customer roles (it would be optimal if WooCommerce did it on its own, but it does not).

So my problem is that the code I have works perfect except that I don't know how to implement a change to calculate zero taxes if the customer is administrator OR reseller.

Here is the code That I am using:

function wc_diff_rate_for_user( $tax_class, $product ) {

    if ( is_user_logged_in() && current_user_can( 'administrator' ) ) {
        $tax_class = 'Zero Rate';
    }
    return $tax_class;
}

add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );

How can I modify this code to make it work, for that users roles?

Thanks


Solution

  • 2020 update

    Try this customized function based on your code where I get first the current user roles. Then I use in_array() php conditional function in an if statement to compare your 2 targeted roles with the current user roles. This way I enable or not this 'Zero rate' tax class.

    Here is the code:

    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( 'reseller', $current_user_data->roles ) )
            $tax_class = 'zero-rate';
    
        return $tax_class;
    }
    add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
    

    Update - Since WooCommerce 3 use the following instead:

    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( 'reseller', $current_user_data->roles ) )
            $tax_class = 'zero-rate';
    
        return $tax_class;
    }
    add_filter( 'woocommerce_product_get_tax_class', 'wc_diff_rate_for_user', 10, 2 );
    add_filter( 'woocommerce_product_variation_get_tax_class', 'wc_diff_rate_for_user', 10, 2 );
    

    This code goes in functions.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested and fully functional.