Support » Plugin: WP-PostRatings » Category Average

  • Hi,
    Can you suggest a way to get the sum of all post ratings in a category and then get the average ratings of all posts in that category?

    Thanks in advance!

Viewing 1 replies (of 1 total)
  • Cat

    (@stitchyrocks)

    I did something like this:

       // Set up an empty array to store average rating for each entry 
        // Run a WP query for entries in this category and find its average rating
        $cat_avg_rating = array();
        $cat_query = new WP_Query( array (
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'cat' => 1234,
        ));
        if ( $cat_query->have_posts() ) : 
            while ( $cat_query->have_posts() ) : $cat_query->the_post(); 
                $cat_avg_rating[] = get_post_meta( get_the_ID(), 'ratings_average', true );
            endwhile; wp_reset_postdata();
        endif;
        // Remove empty vals and calculate average
        $cat_avg_rating = array_filter($cat_avg_rating, function($x) { return $x !== ''; });
        $average = array_sum($cat_avg_rating) / count($cat_avg_rating);
        echo $average;
    
Viewing 1 replies (of 1 total)
  • The topic ‘Category Average’ is closed to new replies.