【问题标题】:How to activate “Zero rate” tax class in WooCommerce based on user role and product category如何根据用户角色和产品类别在 WooCommerce 中激活“零税率”税类
【发布时间】:2021-08-12 20:16:00
【问题描述】:

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

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

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

这是我正在使用的代码:

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

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

【问题讨论】:

标签: php wordpress woocommerce categories user-roles


【解决方案1】:

您可以使用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 );

【讨论】:

    猜你喜欢
    • 2016-05-04
    • 2017-02-11
    • 2017-04-13
    • 2017-10-18
    • 2021-11-30
    • 2023-03-20
    • 2017-06-30
    • 2020-11-17
    • 1970-01-01
    相关资源
    最近更新 更多