WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using the GD Star Rating plugin and the bbPress plugin. The first plugin do have a argument to sort posts by number of votes. But unfortunately, It doesn't work with WP_Query (and apparently the bbPress loop uses it).

That's why I wanted to create my own way of sorting custom post types in a custom loop.

Let's say I have a function or a variable that outputs the number of votes of each post:

<?php votes_number(); ?> or $votes_number

How can I use them in something like this:

query_posts( "orderby=votes_number" );


query_posts( "my_custom_orderby=votes_number" );
share|improve this question
Where is number of votes stores? – Alexey Sep 22 '11 at 22:24
up vote 1 down vote accepted

To order using post based custom fields you have to store your variable in an actual field using add_post_meta or update_post_meta, or manually add it to the post field.

That way you can use WP Query to query the meta value for that field and order by the value. For example;

//adds a value to a field with the key name 'vote_field' and your variable.
<?php add_post_meta($post_id, 'vote_field', $votes_number); ?>

//query the key 'vote_field' and order by
$query = new WP_Query( array ( 
                             'post_type' => 'post', 
                             'meta_key' => 'vote_field', 
                             'orderby' => 'meta_value', 
                             'order' => 'ASC' ) );

Also there are additonal paramters you can use such as meta_value_num and 'meta_compare'

share|improve this answer
Hey thanks I think that's exactly what I needed. One more thing, how can I use that to sort posts by including the query in the URL. For instance, www.mysite.com/blog?orderby=meta_value? – janoChen Sep 23 '11 at 3:22
the orderby=meta_value needs to know the meta_key on order to know where to look. – Wyck Sep 23 '11 at 4:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.