WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using some code I found online to calculate the average value across all posts for [a_custom_field].

Does anyone know how to exclude (from calculation) any instances where the custom field = 0 or if the custom field has not been filled in? Or maybe there's a better method to get the same result.

    global $wp_query;
        $real_query = $wp_query->query; //save reall query
        //create new query for all posts of the tag/category/whatever
        $args = array_merge( $wp_query->query, array( 'posts_per_page' => '-1' ) );

        $average_q = new WP_Query($args);
        $price_count = 0;
        $total_price = 0;
        while ($average_q->have_posts()){
        $total_price = $total_price + get_post_meta($post->ID,'60mins',true);
        $price_count = $price_count + 1;}

        $average = $total_price / $price_count; 

        echo 'The average is' . round($average);
share|improve this question
Can't you just store the get_post_meta return value and check it? – KDM Jun 11 '12 at 4:25
I wasn't sure what I was supposed to do where. But @fdsa's code help me out. All is working now. Thanks to both of you. – TheLoneCuber Jun 11 '12 at 5:35
up vote 0 down vote accepted

Just tell the loop to continue if the custom field is 0 or blank.

if ((get_post_meta($post->ID,'60mins',true))||/*however it returns as blank*/)

This will prevent it from being factored into the average.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.