Support » How-To and Troubleshooting » Sum custom_meta value of all posts

Sum custom_meta value of all posts

Viewing 3 replies - 1 through 3 (of 3 total)
  • 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.

    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.

    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?

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Sum custom_meta value of all posts’ is closed to new replies.
Skip to toolbar