I have 2 custom post types ‘bookmarks’ and ‘snippets’ and a shared taxonomy ‘tag’. I can generate a list of all terms in the taxonomy with get_terms(), but I can’t figure out how to limit the list to the post type. What I’m basically looking for is something like this:
get_terms(array('taxonomy' => 'tag', 'post_type' => 'snippet'));
Is there a way to achieve this? Ideas are greatly appreciated!!
Oh, I’m on WP 3.1.1
Here is another way to do something similar, with one SQL query:
So it just happens that I needed something like that for a project I’m working on. I simply wrote a query to select all posts of a custom type, then I check what are the actual terms of my taxonomy they are using.
Then I got all terms of that taxonomy using
get_terms()
and then I only used those that were in both of the lists, wrapped it up in a function and I was done.But then I needed more then just the ID’s: I needed the names so I added a new argument named
$fields
so I could tell the function what to return. Then I figured thatget_terms
accepts many arguments and my function was limited to simply terms that are being used by a post type so I added one moreif
statement and there you go:The Function:
Usage:
If you only need a list of term id’s then:
If you only need a list of term names then:
If you only need a list of term objects then:
And if you need to use extra arguments of get_terms like: orderby, order, hierarchical …
Enjoy!
Update:
To fix the term count to specific post type change:
to:
Great question and solid answers.
I really liked the approach by @jessica using the terms_clauses filter, because it extends the get_terms function in a very reasonable way.
My code is a continuation of her idea, with some sql from @braydon to reduce duplicates. It also allows for an array of post_types:
Because get_terms doesn’t have a clause for GROUPY BY, I had to add it to the end of the WHERE clause. Notice that I have the filter priority set very-high, in hopes it will always go last.
I wrote a function that allows you to pass
post_type
in the$args
array to theget_terms()
function:HT to @braydon for writing the SQL.
I was unable to make the get_terms arguments to work with Gavin’s version of the code above, but finally did by changing
to
as it was in the original function from Bainternet.
@Bainternet: Thanks! I had to alter the function slightly because it wasn’t working (some typos). The only problem now is that the term count is off. The count isn’t taking the post type into consideration so I don’t think you can use get_terms() in this.
EDIT: Added the fix(es). But somehow it’s still not working for me. The count still shows the incorrect value.
Avoid Duplicates: