Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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()){
        $average_q->the_post();
        $total_price = $total_price + get_post_meta($post->ID,'60mins',true);
        $price_count = $price_count + 1;}

        wp_reset_query();
        $average = $total_price / $price_count; 


        echo 'The average is' . round($average);
        query_posts($real_query);
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

1 Answer 1

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*/)
{
    continue;
}

This will prevent it from being factored into the average.

share|improve this answer

Your Answer

 
discard

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.