Advanced sorting of posts by ratings

GD Star Rating supports expanding of WordPress Query with several variables allowing you to sort posts using ratings. It works with all types of ratings, and it’s easy to set up. But regular method can be problematic for some uses, so here is the advanced method to do same thing.

You can check out old article on GD Star Rating official website here. This one is using query_posts() function and passing parameters to it. But, this method lacks several things that you might need: paging to work for one thing. This function overwrites whole WP_Query, and since it’s run after the WP_Query is initialized, you loose some of the parameters already sate, like paging. Also, it can cause search to stop working, because of the same problem.

This advanced method is very similar, but, this time we are modifying WP_Query before the posts are retrieved in the first place. Code I am adding bellow needs to go into functions.php for a theme. For this example, variables will be set for home and search page. If you need something else you can modify the IF line to include different rules for using the sorting. This method will preserve all the other variables in WP_Query and only adds new parameters for sorting. Also, notice that I have set filter priority to 1, so that this filter function is run before same filter is running inside GD Star Rating.

[sourcecode language=”php”]<?php
add_filter(‘pre_get_posts’, ‘gdsr_get_posts’, 1);

function gdsr_get_posts($wp_query) {
if (is_home() || is_search()) {
$wp_query->set(‘gdsr_sort’, ‘thumbs’);
$wp_query->set(‘gdsr_order’, ‘desc’);
}
}
?>[/sourcecode]

This code is sorting posts in the loop by thumbs ratings in descending order. You can change what is used for sorting by setting variables differently, and list of supported variables is bellow. You can add any of them into the function example above:

  • gdsr_sort: data used for sorting results (rating, review, votes, thumbs,┬álast_voted)
  • gdsr_order: data sorting order (asc, desc)
  • gdsr_multi: standard or multi ratings data to use (multi set id if you want to set by multi rating/review results)
  • gdsr_fsvmin: filter to specify minimal number of standard rating votes
  • gdsr_ftvmin: filter to specify minimal number of thumbs rating votes

Comments

Leave a Reply