Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

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.

share|improve this answer
    
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
    
Thanks! will do! :) –  wpStudent Nov 27 '10 at 19:43

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)
share|improve this answer
    
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

 
discard

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.