对特定产品 ID 的每个用户角色征税 class "Zero rate"

Tax class "Zero rate" per user role on specific product ID's

我得到了这个代码,无论他们订购什么,都可以对用户角色应用免税,这很好。

但现在我需要另一个用户角色,可以对特定产品 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.

案例 1 通过代码

你可以像

一样使用add role函数
<?php add_role( $role, $display_name, $capabilities ); ?>

示例

add_role('basic_contributor', 'Basic Contributor', array(
    'read' => true, // True allows that capability
    'edit_posts' => true,
    'delete_posts' => false, // Use false to explicitly deny
));

案例 2: 通过插件

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

以下是将对某些定义的产品和某些定义的用户角色应用此 "Zero Rate" 税 class 的代码:

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 文件。