且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WooCommerce-启用“零费率"某些特定用户角色的税种

更新时间:2023-11-30 11:45:46

2020更新

尝试使用基于您的代码的自定义功能,我将首先获得当前的用户角色.然后,我在if语句中使用 in_array() php条件函数将您的2个目标角色与当前用户角色进行比较.通过这种方式,我可以启用或禁用此零费率"税收类别.

Try this customized function based on your code where I get first the current user roles. Then I use in_array() php conditional function in an if statement to compare your 2 targeted roles with the current user roles. This way I enable or not this 'Zero rate' tax class.

这是代码:

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( 'administrator', $current_user_data->roles ) || in_array( 'reseller', $current_user_data->roles ) )
        $tax_class = 'Zero Rate';

    return $tax_class;
}
add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );

更新-由于WooCommerce 3改为使用以下内容:

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

此代码包含在活动子主题(或主题)的functions.php文件或任何插件文件中.

This code goes in functions.php file of your active child theme (or theme) or also in any plugin file.

此代码已经过测试,功能齐全.

This code is tested and fully functional.