Ayyaz Zafar Ayyaz Zafar - 1 year ago 114
PHP Question

Woocommerce: How to Add extra fee for First Order

I am trying to add Extra Fee in the total of cart/order amount only if this is first order of Customer.

I searched a lot online but I still did not find any specific solution yet.

Please someone suggest/guide the best solution to perferm this.


Answer Source

You use the cart class' add_fee() method to add a fee. There's no built-in way to know how many orders a customer has made, so we can try to track that via a user meta field called _number_order.

function so_27969258_add_cart_fee() {
    $orders = intval( get_user_meta( get_current_user_id(), '_number_orders', true ) );
    if( $orders < 1 ){
        WC()->cart->add_fee( __( 'First time fee', 'your-plugin'), 100 );
add_action( 'woocommerce_before_calculate_totals', 'so_27969258_add_cart_fee' );

If we don't actually update the _number_orders key, then it will always be null/empty/zero and the user will always be charged the first time fee. So we can try to update that key when the user completes payment.

function so_27969258_track_orders_per_customer(){
    $orders = intval( get_user_meta( get_current_user_id(), '_number_orders', true ) );
    $orders = $orders + 1;
    update_user_meta( get_current_user_id(), '_number_orders', $orders );
add_action( 'woocommerce_payment_complete', 'so_27969258_track_orders_per_customer' );

This is totally untested, so use at your own risk. Also, you might want to look into changing the number of orders total in case of refunds/cancellations, etc, but this seems like the general gist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download