WordPress custom query with ratings

If you have a template that uses WordPress WP_Query object (or query_posts function), you can expand it to display rating and/or sort posts by rating.

Basic Query

We will start with the standard and basic WordPress posts loop using the WP_Query object. This looks like this:

<?php

// query arguments
$args = array();

// query setup
$the_query = new WP_Query($args);

// the query loop
if ($the_query->have_posts()) {
  while ($the_query->have_posts()) {
    $the_query->the_post();

    // display the current post in the loop
    // this example loads the content-post.php file,
    // modify the display for your use case
    get_template_part('content', 'post');
  }
}

wp_reset_postdata();

Line 4 is used to specify filtering arguments for the WP_Query, and to get more information about customizing these arguments, check out official WordPress Codex.

Rating expanded loop

Now, we can expand the loop to display rating blocks and to order the query results using ratings. This example will work with standard stars rating method. In line 4, we need to add arguments to expand the query object with sorting by rating elements.

<?php

// query arguments
$args = array(
  'orderby' => 'gdrts',
  'order' => 'DESC',
  'gdrts_method' => 'stars-rating'
);

// query setup
$the_query = new WP_Query($args);

// the query loop
if ($the_query->have_posts()) {
  while ($the_query->have_posts()) {
    $the_query->the_post();

    // display the current post in the loop
    get_template_part('content', 'post');

    // now, we show the rating block
    gdrts_posts_render_rating(
      array('echo' => true, 'method' => 'stars-rating'),
      array('template' => 'default', 'style_size' => 24)
    );
  }
}

wp_reset_postdata();

WP_Query arguments are expanded to change results sorting order to use GD Rating System data, and we are using Stars Rating method for that. Finally, inside the loop, we have a function call to render the rating block. The function used is made for loops, and will automatically detect post inside the loop.

1
0
343
Rate this article

You are not allowed to rate this post.

Comments

Leave a Reply