Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
?>
share|improve this question
1  
What have you tried so far? Where didn't it work? Btw, so far it's off topic, as it's plain Math and PHP. –  kaiser Oct 2 '13 at 16:49
1  
Edited the answer so I can put code. Thanks!!!! –  KalymaStudio Oct 2 '13 at 17:02

1 Answer 1

up vote 2 down vote accepted

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);
share|improve this answer
2  
Please add an explanation to your answer: why could that solve the problem? –  toscho Oct 2 '13 at 19:50
    
Also, where put that code, because I have already a foreach for each term, and a while for each post in that term. The problem I face, is becasue it don't stop the loop, and continues sum the ammount between terms. –  KalymaStudio Oct 3 '13 at 11:56
    
The problem is you're not declaring it properly and the conditional applies only to the add factor. Edited my answer for better clarification. –  Ervald Oct 3 '13 at 15:23
    
Yeah, but, when I put that code into the loop, it continues sum through terms... Maybe declaring the total and count before loop should fix that? I will try, thanks. –  KalymaStudio Oct 4 '13 at 11:42
    
Don't work. You can see it here: julioiturre.com/biodonostia/areas_investigacion/oncologia/… It continues sum through entirely taxonomy, no in the query result. Help! –  KalymaStudio Oct 7 '13 at 16:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.