Additional price based on cart item count in WooCommerce



PHP Snippet 1:

// Add a custom packing fee based on item count
add_action( 'woocommerce_cart_calculate_fees', 'custom_packing_fee', 10, 1 );
function custom_packing_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
        return;

    $count = $cart->get_cart_contents_count();

    if ( $count >= 9 ){
        $fee = 15;
    }
    elseif( $count >= 6 && $count < 9 ){
        $fee = 14;
    }
    elseif( $count >= 4 && $count < 6 ){
        $fee = 13;
    }

    if ( isset($fee) && $fee > 0 ) {
        $label = sprintf( __('Box fee (%d items)'), $count);
        $cart->add_fee( $label, $fee, false );
    }
}