2016-11-29 38 views
3

我得到了這個代碼,無論用戶指定什麼內容,都可以在用戶角色上免稅。特定產品ID上的每個用戶角色的稅率等級「零率」

但現在我需要另一個用戶角色,將免稅對特定產品ID,我不知道如何實現這一點。

使用的是現在對所有產品針對特定用戶角色免稅代碼IM是:

// 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. 
+0

你需要角色??? –

+0

是的,我只需要一個(或兩個)用戶角色就可以獲得特定產品ID的免費稅 –

回答

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

+0

你是真棒男人,我還沒有測試過,但我會盡快完成並讓你知道! –

+0

是的,我正在做幾個不同的項目,我對很多事情都有一些疑問,這就是爲什麼,但我會盡快公佈結果,再次感謝 –

0

CASE 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/

+0

嗨,感謝您的信息,但你似乎不明白我的問題。我知道如何創建角色,但我需要的是一個特定的用戶角色,對特定的產品ID免稅。 –

+0

好的,那麼你已經編碼爲 –

+0

https://wordpress.org/support/topic/tax-exempt-checkbox-user-still-charged-tax/ –

相關問題