Order by custom field (numeric) in WP_Query

11,820

Solution 1

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.

Solution 2

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

Share:
11,820

Related videos on Youtube

Konsole
Author by

Konsole

I am not sure what I am doing 🤷‍♂️

Updated on September 15, 2022

Comments

  • Konsole
    Konsole almost 2 years

    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

  • GigiSan
    GigiSan almost 6 years
    Thanks, just what I needed! But I presume it's missing a couple commas? :)