如何根据用户角色和产品类别在 WooCommerce 中激活“零税率”税 class

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

在我正在开发的 WooCommerce 网站上,我不仅会向最终客户销售产品,还会向经销商销售产品。

问题是经销商免税,因此我需要一个自定义功能来为某些类型的用户激活零税率。

所以,我的问题是我的代码可以完美运行(当用户是管理员或经销商时),但我不知道如何才能让这些更改仅反映在一个产品类别中(葡萄酒) ).

这是我使用的代码:

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

如何扩展此代码以便它也检查产品类别?

您可以使用 has_term() WordPress 条件函数来检查类别,例如:

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