I have created a theme with a custom post type of reports
. I installed a rating plugin that interacts with this post type, allowing users to rate the reports. It stores the post rating in two fields, sum
and count
where sum is the total for all ratings, and count is the number of individual ratings.
Example: If a 5 people rated a post as 1, 2, 3, 4, and 5, the sum
would be 15
and the count
would be 5
.
When a user visits the reports
archive page, they see a list of all posts of the report
post type. However, I want to add a query parameter to filter down to posts with an average rating of 4 or higher. I'm currently trying to use the pre_get_posts
hook as follows:
add_filter( 'pre_get_posts', 'filterReports' );
function filterReports( $query ) {
if( is_post_type_archive( 'reports' ) && $_GET['top'] ) {
global $wpdb;
$query = $wpdb->prepare(
"SELECT *
FROM
wp_postmeta AS sum
wp_postmeta AS count
WHERE
sum.meta_key = 'sum' AND
count.meta_key = 'count' AND
sum.meta_value / count.meta_value >= 4"
);
}
}
I'm not entirely sure how to construct my custom query in the above. Any advice would be greatly appreciated.