I'm adding voting features to a theme. Visitors can vote posts Up or Down. I created a table for storing number of votes for each post and that works fine. Now I'm trying to sort posts by their votes.

I have "voted up" and "voted down" links. For instance, when you click on "voted up" a new parameter sort=up is passed in the URL.

In the loop if the parameter exists and is = "up" I want to loop posts with votes up.

wpdb->get_results("SELECT post_id, FROM $wpdb->votes WHERE up > 5");

This is where I want to use something like query_posts('sort=up') before the loop. My question is, how to I create the custom "sort" parameter?


If you have your data in separate table adding support for it in query is somewhat messy. Basically you will need to filter posts_where and posts_join to modify raw SQL query so that your custom table is joined and checked against your custom values.

As per [faster :)] anu's suggestion it would make sense to store values in Custom Fields and use Custom Field Parameters (related to Orderby, but not same thing) in query.

  • Thanks for the suggestion! I know I can query anything I need using $wpdb but I thought using query_posts() would be easier to integrate in any theme since I have to add it just before the loop. – wpStudent Nov 27 '10 at 18:44
  • I didn't mean using $wpdb for raw SQL query, I meant using filters to modify internal SQL query that query_posts() generates. This is advanced topic so it is hard to come up with definitive example/documentation, see Custom Queries for starters. – Rarst Nov 27 '10 at 19:20

I'm pretty sure that the only way of doing this using the orderby parameter is to store the vote values in a custom field.

From the Codex (http://codex.wordpress.org/Function_Reference/query_posts#Orderby_Parameters)

OrderBy Parameters

  • orderby=meta_value Note: A meta_key=keyname must also be present in the query. Note also that the sorting will be alphabetical
  • orderby=meta_value_num - Order by numeric meta value (available with Version 2.8)
  • Thanks! Perhaps I'll store votes in the custom fields table although custom fields aren't ideal for this specific voting feature. – wpStudent Nov 27 '10 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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