1
votes

I got great help here in February, regarding a woocommerce issue where I needed an automatic fee added based on total cart height, in this thread.

Now, I also need to add a calculation on item width to the code. But only if any of the items in the cart have a width over 25 cm (not total width since the products are books that are stacked on top of each other, so the extra shipping fees are calculated on total height and width over 25 cm). Examples:

What is working actually:

  • If the total cart height is 3 cm or over, a fee is applied.

What is needed (in addition):

  • If one items width is over 25 cm a fee is applied.
  • If the total cart height is 3 cm or over and if one items width is over 25 cm a fee is applied.

I've been playing around with "Add a fee based on cart items height in Woocommerce" answer code (2nd code snippet), trying to add a height variable to it ($target_width = 25; // ), but I get lost in the calculation, not knowing how to try it without it becoming total cart width and I'm just not qualified to do such an advanced editing of code. All my different attempts didn't work.

Appreciate any help I can get.

1
Code updated: added a missing ; to $width_threshold = 25LoicTheAztec

1 Answers

1
votes

Updated: The following code will handle your additional item with requirement, applying also the fee if a item width is over 25 cm:

add_action( 'woocommerce_cart_calculate_fees', 'shipping_dimensions_fee', 10, 1 );
function shipping_dimensions_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Your settings (here below)
    $target_height   = 3; // The defined height in cm (equal or over)
    $width_threshold = 25; // The defined item with to set the fee.
    $fee             = 50; // The fee amount

    // Initializing variables
    $total_height    = 0; 
    $apply_fee       = false;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        // Calculating total height
        $total_height += $cart_item['data']->get_height() * $cart_item['quantity'];

        // Checking item with
        if ( $cart_item['data']->get_width() > $width_threshold ) {
            $apply_fee = true;
        }
    }

    // Add the fee
    if( $total_height >= $target_height || $apply_fee ) {
        $cart->add_fee( __( 'Dimensions shipping fee' ), $fee, false );
    }
}

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