WordPress.org

Ready to get started?Download WordPress

Forums

Sum custom_meta value of all posts (4 posts)

  1. artinh82
    Member
    Posted 2 years ago #

    I have a custom_meta for each post, named 'project_cost'.
    Is there anyway to loop through all posts and sum the value of all the 'project_cost' ?

    Example
    Post#1 -> 'project_cost' = $100.00
    Post#2 -> 'project_cost' = $200.00
    Post#3 -> 'project_cost' = $150.00
    and so on...

    I want to get the total for all the 'project_cost' values combined, which in this case should be $450.00

    Thank you in advance.

  2. michael.mariart
    Member
    Posted 2 years ago #

    It will need some custom PHP work to do this, but it's not to hard.

    $result = $wpdb->get_results ("SELECT meta_value FROM ".$wpdb->post_meta." WHERE meta_key = 'project-cost'");
    $total = 0;
    foreach ($result as $row) {
       $total += $row->meta_value;
    }
    echo $total;

    Of course... That is assuming that the values for project_cost are stores as plain numbers and not text. if they are text, you can always use something extra like doubleval() to get a numeric value for it.

  3. artinh82
    Member
    Posted 2 years ago #

    Hey Michael,
    Thanks for your reply.

    I just tried the code, and all I get is '0'.

    Maybe this will help... this is the code that I use to display the cost for each project:

    <?php
    	echo '<ul>';
    
    	query_posts('category_name=active-project');
    	while (have_posts()) : the_post();
    
    	$cost = get_post_meta($post->ID, 'project_cost', true);
    	echo '<li>'.$cost.'</li>';
    
    	endwhile;
    
    	echo '</ul>';
    ?>

    The above code will output something like this:
    100.00
    150.00
    120.00
    200.00

    What I need to do, is get the sum of all the above amounts.

  4. michael.mariart
    Member
    Posted 2 years ago #

    In the code that I had in my original post there had 'project-cost' instead of 'project_cost'. That might make a difference.

    What do you get as a result from each row in my code when you make that change?

Topic Closed

This topic has been closed to new replies.

About this Topic