I've read all the WordPress docs that seem relevant, and I've read lots of posts here and on other sites to find an answer to this, but I still can't find a way to do this.

I have a custom post type. My custom post type has meta data. One of those meta data fields is a boolean ( 1 or 0 ), called 'featured', that acts as a flag. I'm trying to create a query for query_posts() (I'll settle for WP_Query if I have to) that first returns the posts that have the flag set (sorted by either date or post ID DESC) and then the posts that do NOT have the flag set (and them also sorted by either date or post ID DESC).

The purpose of this is to have featured posts at the top of the list, sorted by publish date with the most recent posts first, then non-featured posts, also sorted by publish date with the most recent posts first.


a: ID=800, featured=1
b: ID=801, featured=0
c: ID=802, featured=0
d: ID=803, featured=1
e: ID=804, featured=0

This list of posts should be returned to me in the order: d, a, e, c, b

Instead, what I'm getting is: a, d, b, c, e

This is the query code I have so far:

$query = query_posts( array(
    'post_type' => 'my_custom_type',
    'post_status' => 'publish',
    'posts_per_page' => '9',
    'orderby' => array(
        'meta_value_num'    => 'DESC',
        'post_ID' => 'DESC'
    'meta_key' => 'featured'
) ); 

I've tried all sorts of variations on the orderby stuff. I was originally trying to sort on the post date, but tried post ID as it should return the same order and is a simple int. I've flipped DESC to ASC and back again, I've added filters that I've seen suggested in other posts ... no matter what I do, after the initial sort on the flag, the posts are always in ASC order (that is ASC post ID, or ASC post date).

Please help!!

1 Answer 1


I continued to research my issue and ended up finding the solution here: I need query_posts() to order results first by a meta value and then by post ID

Basically, it seems the WordPress orderby is screwed. When I examined the SQL it was producing the orderby looked like this:

ORDER BY wppc_postmeta.meta_value+0 DESC

Which is basically meaningless.

So I created a quick filter function to write the orderby code as WordPress should have done in the first place:

function pb_override_orderby() {
    $orderby_statement = "wppc_postmeta.meta_value DESC, wppc_posts.post_date_gmt DESC";
    return $orderby_statement;

Then, immediately before I make the query_posts() call I add the line:

add_filter('posts_orderby', 'pb_override_orderby');

These two snippets throw out the WordPress bad code and replace it with correct code that works as required. Much better. Something for WordPress to look into in some future bug fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.