基于用户角色或 WooCommerce 中的自定义数据的额外购物车费用

Extra cart fee based on user role or custom data in WooCommerce

我正在寻找一种方法来为 WooCommerce 中的特定用户角色添加额外的 cart/tax 费用。我正在使用 WooCommerce PDF Invoices & Packing Slips 插件。 此费用至少应添加到发送给用户的电子邮件和随附的 PDF 发票中。

我看了下面的代码,觉得可以用。我只是不明白如何为产品添加不同的 'tax classes'。 所以现在发生的是根本没有加税。

 add_filter( 'woocommerce_before_cart_contents', 'wc_diff_rate_for_user', 1, 2 );
 add_filter( 'woocommerce_before_shipping_calculator', 'wc_diff_rate_for_user', 1, 2);
 add_filter( 'woocommerce_before_checkout_billing_form', 'wc_diff_rate_for_user', 1, 2 );
 add_filter( 'woocommerce_product_tax_class', 'wc_diff_rate_for_user', 1, 2 );
 function wc_diff_rate_for_user( $tax_class ) {

if ( !is_user_logged_in() || current_user_can( 'customer' ) ) {
    $tax_class = 'Zero Rate';
}
return $tax_class;
}

我希望任何人都可以帮助我。

更新:您使用的代码已过时,不需要这样做。尝试以下示例,该示例将根据用户角色添加百分比费用:

add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee( $cart ) {
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) )  )
        return;

    // Get current WP_User Object
    $user = wp_get_current_user();

    // For "customer" user role
    if ( in_array( 'customer', $user->roles ) ) {
        $percent = 5; // <== HERE set the percentage
        $cart->add_fee( __( 'Fee', 'woocommerce')." ($percent%)", ($cart->get_subtotal() * $percent / 100), true );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。