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
WP_Query Arguments should be:
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 thewp_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. 2348There 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 waysOne 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 objectglobal $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();
andget_posts()
but these two also uses thewp_query()
Working of
query_posts()
Working of
get_posts()
So last option is to go with
$wpdb
wpdb
for examle order users by points
Important : ABS(meta_value) < for Numeric Order
this is best way 😉