Order by custom field (numeric) in WP_Query

I am using following query to get all posts with post_type 'portfolio'.

$args = array( 
           'posts_per_page' => -1, 
           'offset'=> 0,
           'post_type' => 'portfolio'
         );

$all_posts = new WP_Query($args);

Where $args is:

$args = array( 
               'posts_per_page' => -1, 
               'offset'=> 0,
               'post_type' => 'portfolio',
               'orderby' => 'up_count', //up_count is numeric field from posts table
               'order' => DESC
             );

This should sort the results by up_count. But that's not the case. The codex for wp_query doesn't clearly state about sorting with custom field (or may be I am missing something?).

This is the query I get when debugging wp_query request.

SELECT ap_posts.* FROM ap_posts  WHERE 1=1  AND ap_posts.post_type = 'portfolio' AND (ap_posts.post_status = 'publish' OR ap_posts.post_status = 'private')  ORDER BY ap_posts.post_date DESC  

EDIT: up_count is an extra field of type int in table posts table.

P.S. I am using wordpress ver. 3.5.2

Answers


WP_Query Arguments should be:

$args = array( 
    'posts_per_page' => -1, 
    'offset'         => 0,    
    'post_type'      => 'portfolio',
    'meta_key'       => 'up_count'
    'orderby'        => 'meta_value_num'
    'order'          => 'DESC',
);

All this is written in the Codex, but you need to read many times to understand.


While reviewing the query.php which actually in action when you call the wp_query while reviewing the whole cycle for the processing of $args passed in the wp_query there is the limitation in this method you can only order the posts with the below hardcoded array of fields which is located at line no. 2348

$allowed_keys = array('name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count');
if ( ! in_array($orderby, $allowed_keys) )
                    continue;
  // here your order by fails

There is the switch cases for the above array values so if you have altered the wp_posts table and you want to order the results with this custom field there will be two ways

  • One way is your filed name should have the prefix post_ like post_up_count and in above array add the additional value like

    $allowed_keys = array('name', 'author', 'date', 'title','up_count' ,'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count');

  • Second is to write the custom query and use $wpdb class object

    global $wpdb;

    $wpdb->get_results("SELECT ap_posts.* FROM ap_posts WHERE 1=1 AND ap_posts.post_type = 'portfolio' AND (ap_posts.post_status = 'publish' OR ap_posts.post_status = 'private') ORDER BY ap_posts.up_count DESC ");

As there are other two more functions to fetch posts like query_posts(); and get_posts() but these two also uses the wp_query()

Working of query_posts()

function query_posts($query) {
    $GLOBALS['wp_query'] = new WP_Query();
    return $GLOBALS['wp_query']->query($query);
}

Working of get_posts()

function get_posts($args = null) {
    $defaults = array(
        'numberposts' => 5, 'offset' => 0,
        'category' => 0, 'orderby' => 'post_date',
        'order' => 'DESC', 'include' => array(),
        'exclude' => array(), 'meta_key' => '',
        'meta_value' =>'', 'post_type' => 'post',
        'suppress_filters' => true
    );

    $r = wp_parse_args( $args, $defaults );
    if ( empty( $r['post_status'] ) )
        $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
    if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
        $r['posts_per_page'] = $r['numberposts'];
    if ( ! empty($r['category']) )
        $r['cat'] = $r['category'];
    if ( ! empty($r['include']) ) {
        $incposts = wp_parse_id_list( $r['include'] );
        $r['posts_per_page'] = count($incposts);  // only the number of posts included
        $r['post__in'] = $incposts;
    } elseif ( ! empty($r['exclude']) )
        $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );

    $r['ignore_sticky_posts'] = true;
    $r['no_found_rows'] = true;

    $get_posts = new WP_Query;
    return $get_posts->query($r);

}

So last option is to go with $wpdb wpdb


for examle order users by points

global $wpdb;
$order = $wpdb->get_results("
SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE meta_key='userpoint' ORDER BY ABS(meta_value) DESC", "ARRAY_N
");

Important : ABS(meta_value) < for Numeric Order

this is best way ;)


Need Your Help

Read Jon Skeet's chapter on references versus values. Still confused

c# c++ optimization reference

I read section 2.3.2 of Skeet's book and, from my understanding, there is no such thing as a true reference in C#, like there is in C++.

How to convert an 8-bit OpenCV IplImage* to a 32-bit IplImage*?

opencv iplimage bpp bits-per-pixel

I need to convert an 8-bit IplImage to a 32-bits IplImage. Using documentation from all over the web I've tried the following things: