Chriz Canada Chriz Canada - 5 months ago 11
PHP Question

How to add a surcharge based on the delivery of state?

Per http://docs.woothemes.com/document/add-a-surcharge-to-cart-and-checkout-uses-fees-api/

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;

$county = array('ME');
$percentage = 0.01;

if ( in_array( $woocommerce->customer->get_shipping_state(), $state ) ) :
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, 'standard' );
endif;

}


How do I add more than one state? So if the person is in OH or FL - I'd like to add a rate for each state.

Answer

Write some new code for it...I'll do it for you this time:

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    $state = $woocommerce->customer->get_shipping_state();

    if ( $state == 'ME' ) {
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * 0.01;
        $woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, 'standard' );
    } elseif ( $state == 'OH' ) {
        // Do something else
    } elseif ( in_array( $state, array('FL', 'CA') ) ) {
        // Even something else
    }
}
Comments