Support

Account

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