Categories
Code Snippets WordPress

WooCommerce Shipping Options Based on Weight

WooCommerce shipping options based on weight can be accomplished by creating a callback function for the woocommerce_cart_shipping_packages filter. The filter hook allows you to make a change to the cart package such as conditional shipping options based on shipping class, location, or weight.

To get the weight of all the products in the shopping cart you can use the cart_contents_weight method of the WooCommerce Cart class. The code below will allow only UPS shipping method if the weight is great than 4 pounds. If the weight is below 4 pounds USPS will be the only shipping options. The shipping options can be changed on lines 15 and 30. The weight condition can be changed on line 13.

/** 
 * Shipping based on cart contents weight
 */
add_filter( 'woocommerce_cart_shipping_packages', 'ps_woocommerce_cart_shipping_packages_by_weight' );

function ps_woocommerce_cart_shipping_packages_by_weight( $packages ) {

    $packages = array();
 
  
    $cart_items = WC()->cart->get_cart(); 
   
   if( WC()->cart->cart_contents_weight > 4){
        $packages[] = array(
            'ship_via' => array( 'ups'  ), /*Shipping methods that are available for order over 4 lbs */
            'contents' => $cart_items,
            'contents_cost' => array_sum( wp_list_pluck( $cart_items, 'line_total' ) ),
            'applied_coupons' => WC()->cart->applied_coupons,
            'destination' => array(
                'country' => WC()->customer->get_shipping_country(),
                'state' => WC()->customer->get_shipping_state(),
                'postcode' => WC()->customer->get_shipping_postcode(),
                'city' => WC()->customer->get_shipping_city(),
                'address' => WC()->customer->get_shipping_address(),
                'address_2' => WC()->customer->get_shipping_address_2()
            )
        );
    }else{
       $packages[] = array(
            'ship_via' => array('usps'), /*Shipping methods that are available for order under 4 lbs */
            'contents' => $cart_items,
            'contents_cost' => array_sum( wp_list_pluck( $cart_items, 'line_total' ) ),
            'applied_coupons' => WC()->cart->applied_coupons,
            'destination' => array(
                'country' => WC()->customer->get_shipping_country(),
                'state' => WC()->customer->get_shipping_state(),
                'postcode' => WC()->customer->get_shipping_postcode(),
                'city' => WC()->customer->get_shipping_city(),
                'address' => WC()->customer->get_shipping_address(),
                'address_2' => WC()->customer->get_shipping_address_2()
            )
        ); 
    }
      
    return $packages;
}

Subscribe To Updates and Tips Via Email

Get tips on web development, WordPress, web design & more