【问题标题】:Tax class "Zero rate" per user role on specific product ID's特定产品 ID 上每个用户角色的税级“零税率”
【发布时间】:2017-04-13 18:51:42
【问题描述】:

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

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

【问题讨论】:

  • 是的,我只需要一个(或两个)用户角色就可以对特定产品 ID 免税

标签: php wordpress woocommerce checkout cart


【解决方案1】:

以下代码将为某些已定义的产品和某些已定义的用户角色应用此“零税率”税类:

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

【讨论】:

  • 你太棒了,我还没有测试过,但我会尽快让你知道!
  • 是的,我正在做几个不同的项目,我对很多事情有一些疑问,这就是原因,但我会尽快发布结果,再次非常感谢跨度>
【解决方案2】:

案例 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/

【讨论】:

  • 您好,感谢您提供的信息,但您似乎不明白我的问题。我知道如何创建角色,但我需要一个特定的用户角色才能对特定产品 ID 免税。
  • 不,因为它确实对所有产品征税,而不是对一个且唯一的产品 ID(或者至少不是据我理解的代码)你会指出我在我的代码中的哪个位置是产品 ID 的过滤器吗?
  • 你有产品对象。
  • 我从另一个线程复制了该代码,但我根本不了解 php 代码...我知道我得到了 $product,但我不知道应该在我的代码上添加或修改什么来应用只是在某些产品 ID 上。请帮助我,如果你能修改它,我将非常感激,这样我可能会看到差异并完全理解代码
猜你喜欢
  • 2017-10-18
  • 2017-02-11
  • 2021-08-12
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 2019-07-09
  • 1970-01-01
相关资源
最近更新 更多