Operations with custom fields values in a loop

I have a foreach for displaying all the post in one taxonomy filter by terms.
I have a custom field for display a numeric value.
What I need, is to make two math operation with all the values of that field, across all post in that term.

I mean:

Taxonomy X has 4 terms.
Each term has 4 posts.
Each post, has 1 custom_field.
I need to make the sum of all custom_field value in that term, and the average of that custom field.

So, for now I have:

<?php foreach ( $prod_terms as $prod_term ) {
$prod_query = new WP_Query( array(
 'post_type' => 'prod_cientifica',
 'prod_area' => $post_slug,
 'tax_query' => array(
    array(
    'taxonomy' => 'prod_tipo',
    'terms' => array( $prod_term->slug ),
    'operator' => 'IN',
    'get' => 'all', 
    'field' => 'slug'
    )
)
) );

if ( $prod_query->have_posts() ) : while ( $prod_query->have_posts() ) : $prod_query->the_post(); ?>

<div class="areaItem">
 <h4><?php the_title(); ?></h4>
 <p class="autores"><?php the_field('prod_autores'); ?></p>
 <p class="info"><?php the_field('prod_info'); ?></p>
 <p class="info"><?php the_field('prod_fi'); ?></p>
</div>
<?php endwhile; endif; ?>

What i need, is to make the sum of all prod_fi field in every term. Also, the average of that field too.

Any idea?

Thanks!

— Edit with code.

I tried several options by now. The closer one was this:

<?php
if ( $prod_query->have_posts() ) : while ( $prod_query->have_posts() ) : $prod_query->the_post(); 
$total_fi = array();
$meta_key = 'prod_fi';//set this to your custom field meta key
$total_fi = $wpdb->get_col($wpdb->prepare
    ("SELECT meta_value FROM wp_postmeta as pm
    INNER JOIN wp_term_relationships as tr ON (pm.post_id = tr.object_id) 
    INNER JOIN wp_term_taxonomy as tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
    WHERE 1
    AND tt.taxonomy = 'prod_tipo'
    AND pm.meta_key = %s", 
    $meta_key));
    echo 'Total FI '.array_sum( $total_fi );
    ?>

But, this one shows me the total ammount of all custom_field in taxonomy.

this one, doesn’t stop of sum in each term, it continues.

$factorI = get_field('prod_fi'); 
if($factorI) {$factor_total += $factorI;}
echo $factor_total;

Thank u.


I’ve found a dirty fix to this. I know this is not the way, please if someone knows the right way to do this, I will be happy!!!!

<?php
//start the foreach for each term in taxonomy
foreach ( $prod_terms as $prod_term ) {
$prod_query = new WP_Query( array(
    'post_type' => 'prod_cientifica',
    'prod_area' => $post_slug,
    'tax_query' => array(
         array(
            'taxonomy' => 'prod_tipo',
            'terms' => array( $prod_term->slug ),
            'operator' => 'IN',
            'get' => 'all', 
            'field' => 'slug'
            )
         )
) );
?>
<div class="area">
    <h2><?php echo $prod_term->name; ?></h2>
    <?php 
             // First while for fetch the value of "prod_fi" and make the math.
             while ( $prod_query->have_posts() ) : $prod_query->the_post(); 
        $factorI = get_field('prod_fi'); 
        if($factorI) {$factor_total += $factorI;}
                    // count post for average math operation
        $count_posts = $prod_query->current_post + 1;
        $factorP = $factor_total / $count_posts;
    endwhile; ?>
    <p class="areasPublicados"><?php _e('Publicados: ', 'twentytwelve'); ?> <?php echo $count_posts; ?></p>
    <p class="areasFI fleft"><?php _e('FI medio: ', 'twentytwelve'); ?> <?php echo $factorP; ?> </p><p class="areasFI fright"><?php _e('FI: ', 'twentytwelve'); ?> <?php echo $factor_total; ?></p>

    <?php
             //original query to fetch the post in the term
    if ( $prod_query->have_posts() ) : while ( $prod_query->have_posts() ) : $prod_query->the_post(); ?>
    <div class="areaItem">
        <h4><?php the_title(); ?></h4>
        <p class="autores"><?php the_field('prod_autores'); ?></p>
        <p class="info"><?php the_field('prod_info'); ?></p>
            </div>
     <?php endwhile; endif; ?>
</div>
<?php
// Reset math operation of factor_total, so it don't continue sum
   $factor_total = null;
   $prod_query = null;
   wp_reset_postdata();
 } //endforeach
?>

Edited again!

<?php
 // Fetch all post in taxonomy divided by terms.
 foreach ( $prod_terms as $prod_term ) {
    $prod_query = new WP_Query( array(
    'post_type' => 'prod_cientifica',
    'prod_area' => $post_slug,
    'tax_query' => array(
        array(
        'taxonomy' => 'prod_tipo',
        'terms' => array( $prod_term->slug ),
        'operator' => 'IN',
        'get' => 'all', 
        'field' => 'slug'
        )
    )
) );
?>
<?php if($prod_query->have_posts()) : ?>
    <div class="area">
    <h2><?php echo $prod_term->name; ?></h2>
    <?php 
    // Declare total and count before loop
    $factorTotal = 0;
    $factorCount = 0;
    // First loop to fetch prod_fi value
    while ( $prod_query->have_posts() ) : $prod_query->the_post(); 
                $factorI = get_field('prod_fi'); 
        if($factorI) { // Only if it exists
                  $factorTotal += $factorI; // Add it
                  $factorCount++; // Count it
        }
    endwhile; ?>
    <p class="areasPublicados">
       <?php _e('Publicados: ', 'twentytwelve'); ?> <?php echo $factorCount; ?>
    </p>
    <p class="areasFI fleft">
       <?php _e('FI medio: ', 'twentytwelve'); ?> <?php echo $factorTotal; ?> 
    </p>
    <p class="areasFI fright">
       <?php _e('FI: ', 'twentytwelve'); ?> <?php echo ($factorTotal / $factorCount); ?>
    </p>

    <?php
    if ( $prod_query->have_posts() ) : while ( $prod_query->have_posts() ) : $prod_query->the_post(); ?>
        <div class="areaItem">
        <h4><?php the_title(); ?></h4>
        <p class="autores"><?php the_field('prod_autores'); ?></p>
        <p class="info"><?php the_field('prod_info'); ?></p>
        </div>
    <?php endwhile; endif; ?>
</div>
<?php endif; ?>
<?php
// Reset things, for good measure
$factor_total = null;
$prod_query = null;
wp_reset_postdata();
} //enforeach
?>

Solutions Collecting From Web of "Operations with custom fields values in a loop"

Here is a simple way to do this:

// First declare total and count before the loop
$total = 0;
$count = 0;

foreach($posts as $post)
{
     if(get_field('prod_fi')){ // If we have a value add it to the total and count it
        $total += get_field('prod_fi');
        $count++;
     }
}

echo 'Count: '. $count;
echo 'Total Sum: '. $total;
echo 'Average: '.($total / $count); // To get the average

EDIT:

In your case, where you have the $prod_query loop, hope this makes more sense 🙂

// Declare total and count before loop
$factorTotal = 0;
$factorCount = 0;

while ( $prod_query->have_posts() ) : $prod_query->the_post(); 
    $factorI = get_field('prod_fi'); 
    if($factorI){ // Only if it exists
        $factorTotal += $factorI; // Add it
        $factorCount++; // Count it
    } // end if
endwhile;

echo 'Count: '. $factorCount;
echo 'Total Sum: '. $factorTotal;
echo 'Average: '.($factorTotal / $factorCount);