Order by custom field (numeric) in WP_Query
php, sql, wordpress
Solution
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.
Problem
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