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

泄露秘密 提交于 2019-12-10 10:24:23

问题


I got this code that will apply tax free on a user role regardless of what they order, which is fine.

But now I need another user role that will apply tax free on specific products id, and I'm not sure how to acomplish that.

The code im using right now for tax free on all products for specific user role is:

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


Here is the code that will apply this "Zero Rate" tax class for some defined products and some defined user roles:

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;

}

This code is tested and works.

Code goes in any php file of your active child theme (or theme) or also in any plugin php files.




回答2:


CASE 1 Via code

You can use add role function like

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

Example

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

CASE 2 : Via Plugin

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



来源:https://stackoverflow.com/questions/40871587/tax-class-zero-rate-per-user-role-on-specific-product-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!