Search code examples
phpwordpresswoocommerceproducthook-woocommerce

How to replace woocommerce_product_tax_class deprecated hook?


I'm getting the following error in my error log: woocommerce_product_tax_class is deprecated since version 3.0.0! Use woocommerce_product_get_tax_class instead.

I have the following function to show different user roles different tax classes. Can I literally just change "woocommerce_product_tax_class" to "woocommerce_product_get_tax_class" or does the function need re-writing?

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( 'eu_no_duty', $current_user_data->roles ) )
            $tax_class = 'Zero Rate';
      
      elseif ( in_array( 'eu_no_vat', $current_user_data->roles ) )
            $tax_class = 'Zero Rate';
      
      elseif ( in_array( 'eu_trusted', $current_user_data->roles ) )
            $tax_class = 'Zero Rate';
    
        return $tax_class;
    }
    add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );

Solution

  • So the hook woocommerce_product_tax_class is deprecated since WooCommerce 3 and replaced by woocommerce_product_get_tax_class and woocommerce_product_variation_get_tax_class hooks instead.

    Use the following simplified code instead:

    add_filter( 'woocommerce_product_get_tax_class', 'tax_rate_based_on_user_role', 10, 2 );
    add_filter( 'woocommerce_product_variation_get_tax_class', 'tax_rate_based_on_user_role', 10, 2 );
    function tax_rate_based_on_user_role( $tax_class, $product ) {
        $roles   = array('eu_no_duty', 'eu_no_vat', 'eu_trusted'); // Here define user roles
        $user    = wp_get_current_user(); // Get current WP_User object 
    
        $matches = array_intersect( $user->roles, $roles ); // Check for matching user roles
    
        if ( ! empty($matches) ) {
            $tax_class = 'Zero Rate';
        }
        return $tax_class;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should better work.