1
votes

I am using Advanced Custom Fields plugin with WooCommerce and I have a custom field get_post_meta( get_the_ID(), "lead_time", true );" for my WooCommerce products. When a person is checking out this field displays the lead time for each product if out of stock.

I need to find the highest "lead time" from all cart items / order items and then show that number as the final lead time on the order.

The following code shows the lead time for all products in the cart,:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    $leadTimes = get_post_meta($cart_item['product_id'] , 'lead_time', true );
    echo $leadTimes;
}

As an example would be 3 products in cart/order:

  • the first has a 7 day lead time,
  • the second has a lead time of 14 days,
  • and the third has a lead time of 7 days.

But it displays 7147.

I would need to display "lead time = 14 days" since 14 is the greatest lead time of the 3 items in cart. I have tried every possible combination that I can think of using the above foreach loop, for 3 days now. With many different results but not the one I need.

Any help would be greatly appreciated.

1

1 Answers

2
votes

Try the following using php max() function:

$lead_time = array(); // Initializing

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
    $lead_time[] = get_post_meta( $cart_item['product_id'], 'lead_time', true);
}

echo '<p>Max Lead time: ' . max($lead_time) . ' days</p>';

You will get the max value (displayed).

Or as you using Advanced Custom Fields, this should also work:

$lead_time = array(); // Initializing

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
    $lead_time[] = get_field('lead_time', $cart_item['product_id']);
}

echo '<p>Max Lead time: ' . max($lead_time) . ' days</p>';