特定产品ID的每个用户角色的税级“零利率”

时间:2016-11-29 17:02:46

标签: php wordpress woocommerce checkout cart

我得到的代码将对用户角色免税,无论他们订购什么,这很好。

但是现在我需要另一个用户角色,它将对特定产品ID 免税,而我不确定如何完成。

我现在使用的代码免税用于特定用户角色的所有产品:

// Apply a different tax rate based on the user role.

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

return $tax_class;
}
add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
// Fin Apply a different tax rate based on the user role.

2 个答案:

答案 0 :(得分:3)

以下是针对某些已定义产品和某些已定义用户角色应用此“零费率”税级的代码:

add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
function wc_diff_rate_for_user( $tax_class, $product ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Define HERE your targeted products IDs
    $products_ids_arr = array(12 ,15, 24);

    // Define HERE your targeted user roles
    $users_role_arr = array('administrator', 'userrolename');

    //Getting the current user data
    $user_data = get_userdata(get_current_user_id());

    foreach ($users_role_arr as $user_role)
        if ( in_array( $user_role, $user_data->roles ) && in_array( $cart_item->id, $products_ids_arr ) ) {
            $tax_class = 'Zero Rate';
            break;
        }

    return $tax_class;

}

此代码经过测试并有效。

代码可以在您的活动子主题(或主题)的任何php文件中,也可以在任何插件的php文件中。

答案 1 :(得分:0)

案例1 通过代码

您可以使用in功能

add role

实施例

<?php add_role( $role, $display_name, $capabilities ); ?>

案例2:通过插件

https://wordpress.org/plugins/user-role-editor/