How to sort posts based on the value (number) of a post’s metadata?

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.

Read More

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" );

or

query_posts( "my_custom_orderby=votes_number" );

Related posts

Leave a Reply

1 comment

  1. 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