Iâm working on a member page where I use a custom post type with a custom taxonomy. My custom post type is called member
and my custom taxonomy is called member_groups
.
I want to list all the members but group them together into their respective groups.
So to be clear, Iâve 35 members divided into 9 groups â so instead of making the same query nine times I want to do it once but group them together, so that Member1, Member4 and Member 11 is grouped together in one group, called âMarketingâ.
Iâm using WP_Query
to retrieve all posts under post type member. Iâve tried different attempts but with no successful result.
How can I achieve that?
So, you might consider automating the multiple queries.
First, get the list of terms in your custom taxonomy, using
get_terms()
:Then, loop through each one, running a new query each time:
I can’t see anything particularly wrong with this approach, though it may have a limited ability to scale (i.e. if you have hundreds or thousands of members, or member_group terms, you may see performance issues).
I found a solution by using a custom query and then grouping it with the term name:
Then by just using a regular foreach query I can just extract the information I want.
But I’m still interested in another way if there is, maybe by using WordPress’ own functions.
even simpler:
Within the resultant $posts array, each tax term is the key to a nested array containing its posts.
I had this exact need, and Chip’s solution worked, except for one thing:
'field' => 'slug'
is required.I also needed the resulting display to be flat, so
'get' => 'all'
is set here.Hopefully this helps somebody else out.
I had to do this on a project years ago. Similar answer to djb, just with a bit more details. This will output all of your taxonomy names as an h3, with a bulleted list of each post title linked to their detail page.
Then when you loop through this query you could just use an if along these lines
(in php pseudocode)
I hope that helps. I think you were making this far more complicated than it needed to be.
More information: http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
Well, it’s an old thread, but if someone passes by as I did, this might help.
The idea is to modify the main query so we don’t need to go the templates and generate new queries and loops…
PS: Yet to be tested in large dbs. It was satisfactory in my case.