WordPress: Calculate custom field values of all posts within a category?

I have a custom post type (product) , which includes a custom number field (rating). On a category (manufacturer) page I want to average those ratings to give an aggregate rating for the manufacturer.

So I am trying to build a function that returns a single value:

Read More
  • retrieves the average value of all non-empty ratings fields found within the custom posts that are categorized with this category
  • runs independently of the loop (I need to display before the loop and sometimes have more posts than are being used by the loop)

Any ideas how to tackle this?

Related posts

Leave a Reply

1 comment

  1. You create custom template which you would apply to your Manufacturers page. Outwith the main loop you would create a secondary loop using WP_Query. You then run through your custom post type and cumulate the ratings where they exist. Set up a counter to calculate the average. Then use wp_reset_query() to reset the loop if necessary.

    I’ve not tested the code below (obviously, I’m not going to go and set all that up), but it should give you enough of an idea that you can tweak/debug it to get the desired result;

    I have created a fictitious category ID within you custom post type of 4 in this example, you can change it to whatever your setup is;

    <?php
    $counter = 0;
    $cumulative_value = 0;
    
    $avg_query = new WP_Query(array('post_type' => 'product', 'posts_per_page' => '-1', 'cat' => '4' ));
    
    if ( $avg_query->have_posts() ) :  
        while ($avg_query->have_posts()) : $avg_query->the_post(); 
    
            if ( $rating_value = get_post_meta($post->ID, 'rating', true) ) :
    
                $cumulative_value += $rating_value;
                $counter++;
    
            endif;
    
        endwhile;
    
    endif;
    
    $avg_value = $cumulative_value/$counter;
    
    wp_reset_query(); ?>