WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a site with two CPT's Projects and Artworks. I use scribu's posts2posts for connecting a bunch of artworks to each project.

In a single Project view, I want to display all connected artworks. But the artworks should be grouped under headings like 'Paintings', 'Videos', etc..

Now, the obvious thing I thought, would be to add a custom taxonomy (work-type) with the terms Paintings', 'Videos' in order to be able to GROUP the artworks by work type.

Using WP_Query(), I can't order by the terms of my taxonomy.

I can query all the connected works, and do some php stuff, to get them sorted out of course, but I'd like to avoid extra calls to the DB, and to use the WP API as much as possible..

What would be an most effective way of achieving what I need? Do I have to construct a custom raw sql query?

share|improve this question
lol working on the exact same thing tonight.. pre_get_posts part is easy, getting all the posts. But grouping them by header... I've yet to find a way to somehow inject a term ID field into each query result post object. – lkraav Jan 26 '13 at 1:52
well for now, I'm fetching all connected posts - unsorted. Then I prepare an array with all possible terms as array keys. I then place each post from the result individually into this other array, where I group them by their term_id (by the array keys). Finally I then create the output from the array holding my posts grouped by terms. This way I can also control the order of the terms. It works, and with minimal calls to the DB, and strict use of WP API, but the code becomes rather long, with lots of foreach loops. – mikkelbreum Jan 26 '13 at 2:05
Right, but how are you getting the result posts term_id-s right now? Solving that with a single query is the tricky part, isn't it. If you loop through posts and hit each one with get_the_terms(), I don't think it's cached at all at that point? – lkraav Jan 26 '13 at 2:10
right, I'm calling wp_get_object_terms once for each post. But for my case here, the rendered page will be cached, so I judge it's ok. – mikkelbreum Jan 26 '13 at 21:35
Cached with transients? – lkraav Jan 26 '13 at 21:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.