Add up all numbers from a WordPress query [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers. This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers. Closed 16 hours ago. Improve this question I have the following code $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $post_id = get_the_ID(); $party_size = get_field('reservation_party_size', $post_id); $numbers .= $party_size; } } return $numbers; And this returns all party sizes after each other like this: 12345 (so without a space of comma). I just want to sum all these numbers to a total (in this example: 15) What I tried: $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $post_id = get_the_ID(); $party_size = get_field('reservation_party_size', $post_id); $numbers .= $party_size; } } $array = array($numbers); return array_sum($array); Also tried: $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $post_id = get_the_ID(); $party_size = get_field('reservation_party_size', $post_id); $numbers .= $party_size; } } $list = implode(', ', $numbers); $array = array($list); return array_sum($array); And I can go on and on.... Getting crazy here. So in short: I have various posts with a custom field called PART_SIZE and I just want to add up all PARTY SIZE field values so I know how many TOTAL people will come over.

Comment (1)

Jese Leos

September 18, 2024

Verified user

Instead of: $numbers .= $party_size; which concats all numbers use an array to collect them, like following: $numbers[] = $party_size; With this array you can use functions like array_sum() to get the sum of all numbers. A string of numbers isn't normally a solution since the numbers can be bigger than 9. Then you can't be sure which number is bigger than 10 and which not. Or if you don't need the numbers anymore after the loop, sum them up in the loop like following (thanks to the comment of C3roe): $query = new WP_Query($args); $numbers = 0; if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $post_id = get_the_ID(); $party_size = get_field('reservation_party_size', $post_id); $numbers += $party_size; } } return $numbers;

You’ll be in good company