简体   繁体   中英

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

I am looking for a way to add an extra cart/tax fee for a specific user role in WooCommerce. I'am using WooCommerce PDF Invoices & Packing Slips plugin. This fee should at least be added to the email that is being send to the user and in the PDF invoice that is send with it.

I took a look at the following code and thought I could use it. I only don't understand how I can add different 'tax classes' to the products. So what happens now is that there's no tax added at all.

 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;
}

I Hope anyone can help me out.

Updated: The code you are using is outdated and not needed for that. Try the following example that will add a percentage fee based on user role:

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 );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM