I'd like to query wp posts in custom way, I'm not sure whether or not WP_Query class can do this, but I'd like order the posts by posts that has a specific custom taxonomy and then continue with the rest of the posts.

I've tried multiple things and tried SQL custom query but I'm not SQL expert so my SQL has an error.

FROM wp_posts AS wpost
INNER JOIN wp_term_relationships ON ( wpost.ID = wp_term_relationships.object_id )
INNER JOIN wp_term_taxonomy ON ( wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id )
AND wp_term_taxonomy.taxonomy = 'location'
AND wp_term_taxonomy.term_id
IN ( 1191 )
FROM wp_posts AS w2post
INNER JOIN wp_term_relationships as wp2rel ON ( w2post.ID = wp2rel.object_id )
INNER JOIN wp_term_taxonomy as wp2tax ON ( wp2rel.term_taxonomy_id = wp2tax.term_taxonomy_id )
AND wp2tax.taxonomy = 'location'
AND wp2tax.term_id
NOT IN ( 1191 )) inn2
ORDER BY wpost.post_date DESC

Could someone help me please? Is there a better solution than this? Can WP_Query do such an order?

  • 1
    This thread might help you out: wordpress.stackexchange.com/questions/14306/… – DrewAPicture Sep 8 '14 at 14:26
  • @DrewAPicture, thanks for your comment, but I don't want to 'order by' I just want to show the posts with a given taxonomy first then show the rest of the query, is that possible even with a custom SQL? – MacLover Sep 8 '14 at 14:31
  • 1
    Honestly, I would probably just use two queries and mash the output together. If you try to do it all at once, it's just going to be needlessly complicated. – DrewAPicture Sep 8 '14 at 14:32
  • To clarify, you want to show posts in a list. You want the posts in that list that have been assigned the term A in taxonomy B, to appear first. Then the posts that have not been assigned the term A in taxonomy B to appear. Correct? – Tom J Nowell Sep 8 '14 at 14:34
  • Here's another single query approach. – birgire Sep 8 '14 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.