0

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);
  • Can't you just store the get_post_meta return value and check it? – Dakshinamurthy Karra 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
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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