• Feel free to laugh but this is driving me crazy. I have spent a lot of time trying to solve what is probably a basic thing in php.

    I want the total from a custom field called loan_amount. The code below gives this type of output:

    Red Donkey Loan Amount: $300
    New Balance: $300
    Tractor Loan Amount: $2000
    New Balance: $2300

    It is returning the correct posts, with the correct values to be considered, and making a running balance. All I want is the final total value, the 2300.

    <?php
    
    // The Query
    $the_query = new WP_Query( array( 'post_type' => 'post', 'cat' => '4',  'meta_key' => 'loan_amount',  'orderby' => 'date', 'order' => 'ASC') );
    
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
    	echo '<li>';
    	the_title();
    $custom_fields = get_post_custom();
    $my_custom_field = $custom_fields['loan_amount'];
     foreach ( $my_custom_field as $key => $value )
     echo " Loan Amount:  $" . $value . "<br />";
    	echo '</li>';
    
    if ($value) {
           $total += $value;
    echo "New Balance: $" . $total . "<br/>";
       }
    endwhile;
    
    // Reset Post Data
    wp_reset_postdata();
    
    ?>

    Any help would be appreciated.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    You need to set $total to zero before the loop starts. You correctly keep a running total in the loop. But you should output the total after the loop is complete, not in the loop.

    (Not laughing, we’ve all been there, it’s crazy making.)

    Thread Starter John

    (@jsing)

    Thanks! It worked like a charm!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Adding values from custom fields from a single category’ is closed to new replies.