WordPress.org

Ready to get started?Download WordPress

Forums

Adding values from custom fields from a single category (3 posts)

  1. jsing
    Member
    Posted 1 year ago #

    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.

  2. bcworkz
    Member
    Posted 1 year ago #

    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.)

  3. jsing
    Member
    Posted 1 year ago #

    Thanks! It worked like a charm!

Topic Closed

This topic has been closed to new replies.

About this Topic