Sum custom_meta value of all posts (4 posts)

  1. artinh82
    Posted 3 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' ?

    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
    Posted 3 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
    Posted 3 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:

    	echo '<ul>';
    	while (have_posts()) : the_post();
    	$cost = get_post_meta($post->ID, 'project_cost', true);
    	echo '<li>'.$cost.'</li>';
    	echo '</ul>';

    The above code will output something like this:

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

  4. michael.mariart
    Posted 3 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