Home › Forums › Front-end Issues › Find Sum of Custom Field Values from Different Posts › Reply To: Find Sum of Custom Field Values from Different Posts
Sorry I left this so long but I’ve only just had chance to have a proper go with this code. It’s taken a lot of fiddling to tweak it to my needs but it’s all sorted now – John I can’t thank you enough for pointing me in the right direction!
For others who need to know how to do this, my working code is below. This is a much simpler example where each post has a custom field of “rating”. We want to automatically get the rating from each post and add them all together to give a total rating.
This goes inside your post loop:
// Get Rating Totals
if (have_rows('text_block')) {
$i = 0;
while(have_rows('text_block')) {
the_row();
$rating = get_sub_field('rating');
$ratingsArray[$i++] += get_sub_field('rating');
}
}
This outputs the total rating and should go outside of the loop:
echo array_sum($ratingsArray);
Cheers
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.