Filipe Martins
Filipe Martins

Reputation: 15

How to activate “Zero rate” tax class in WooCommerce based on user role and product category

On the WooCommerce website that I am developing, I will be selling not only to the end customer, but also to resellers.

The problem is that resellers are exempt from TAXES and therefore I need a custom function to activate the zero tax rate for certain types of users.

So, my problem is that the code I have works perfectly (when the user is an administrator or reseller), but I don't know how to do so that these changes are reflected only in one product category (wine).

Here is the code I am using:

function wc_diff_rate_for_user( $tax_class, $product ) {
    $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 );

How can I extend this code so that it will also check for product category?

Upvotes: 1

Views: 517

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29624

You can use has_term() WordPress conditional function to check for a category like:

function filter_woocommerce_product_get_tax_class( $tax_class, $product ) {
    // Specific categories: the term name/term_id/slug. Several could be added, separated by a comma
    $categories = array( 'wine' );
    
    // Has term (product category)
    if ( has_term( $categories, 'product_cat', $product->get_id() ) ) {
        // Get current user
        $user = wp_get_current_user();
        
        // Roles to check
        $roles_to_check = array( 'administrator', 'reseller' );
        
        // User role is found?
        if ( count( array_intersect( $user->roles, $roles_to_check ) ) > 0 ) {
            $tax_class = 'Zero rate';
        }
    }

    return $tax_class;
}
add_filter( 'woocommerce_product_get_tax_class', 'filter_woocommerce_product_get_tax_class', 10, 2 );
add_filter( 'woocommerce_product_variation_get_tax_class', 'filter_woocommerce_product_get_tax_class', 10, 2 );

Upvotes: 1

Related Questions