简体   繁体   中英

Exclude specific product variation from tax class filter hook in WooCommerce

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 method get_id() as follows:

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 = 1337;
    $targeted_user_role    = 'MEMBER';

    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;
}

Code goes in functions.php file of your active child theme (or active theme). It should works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM