I am trying to apply a specific tax class by role in a wordpress filter. This tax class applies to variation products as well as regular single products. I just need to exclude a specific variation product or production variation by id. Here is what I have so far:
function wc_diff_rate_for_user( $tax_class, $product ) {
$user_id = get_current_user_id();
$user = get_user_by( 'id', $user_id );
if ( is_user_logged_in() && ! empty( $user ) && in_array( 'MEMBER', $user->roles ) && is_product() && get_the_id() != 1337) {
$tax_class = 'Reduced rate';
}
return $tax_class;
}
add_filter( 'woocommerce_product_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );
add_filter( 'woocommerce_product_variation_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );
I think im failing at the following part:
is_product() && get_the_id() != 1337)
as the tax class of 'Reduced rate' is applied to all products including the one im trying to exclude.
Any suggestions would be highly appreciated.
The main problem in your code is
get_the_id()
that can't work for product variations on single variable product pages as it gives the variable product Id but not any product variation id...Instead as you can see in your code, the hooked function has 2 available arguments, so you can use the variable
$product
to get the Id from it using the methodget_id()
as follows:Code goes in functions.php file of your active child theme (or active theme). It should works.