Sort custom post type on average rating
-
Hi Blaz,
I’m using version 3.1.0 of your Rate My Post plugin and it works wonderfully. I use it only on a custom post type called gv_poem. I have been wanting to be able to sort these posts in descending order by average rating (i.e., “Most Popular Poems”).
I couldn’t find anything in your docs or forums, and I’ve been banging my head on the wall with this for ages, but I finally got it to work!
I started the code from this page:
https://codex.www.ads-software.com/Plugin_API/Filter_Reference/posts_orderby
But this is incomplete, as you also have to add a GROUP BY filter to get it to work.
Here is the working code:
add_filter('posts_orderby', 'edit_posts_orderby'); add_filter('posts_join_paged','edit_posts_join_paged'); add_filter( 'posts_groupby', 'edit_posts_groupby' ); function edit_posts_groupby($groupby) { global $wpdb; $analytics = $wpdb->prefix . "rmp_analytics"; $groupby = "$analytics.post"; return $groupby; } function edit_posts_join_paged($join_paged_statement) { global $wpdb; $analytics = $wpdb->prefix . "rmp_analytics"; $join_paged_statement .= "LEFT JOIN $analytics ON $analytics.post = " . $wpdb->prefix . "posts.ID"; return $join_paged_statement; } function edit_posts_orderby($orderby_statement) { global $wpdb; $analytics = $wpdb->prefix . "rmp_analytics"; $orderby_statement = "(SUM($analytics.value)/COUNT($analytics.votes)) DESC"; return $orderby_statement; } $paged = get_query_var( 'paged' ); $args = array( 'post_type' => 'gv_poem', 'post_status' => 'publish', 'posts_per_page' => 24, 'paged' => $paged, ); $query = new WP_Query($args);
I hope you and your users find it helpful. Thanks for creating such an excellent plugin!
- The topic ‘Sort custom post type on average rating’ is closed to new replies.