[wp-hackers] Querying posts for all associated term_ids?

Mike Schinkel mikeschinkel at newclarity.net
Sat Sep 4 20:32:59 UTC 2010


Hi all,

I am trying to figure out if it is possible to use the WordPress database API without having to add hooks to get the distinct list of term IDs from a given taxonomy that are associated with posts of a given post type? 

I looked and could not find any thing available in WordPress core even though it seems that I must be missing something. Here's the SQL code that achieves what I'm after:

SELECT DISTINCT
  tt.term_id
FROM wp_posts p
  INNER JOIN wp_term_relationships tr ON p.ID = tr.object_id
  INNER JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE 1=1
  AND p.post_status='publish'
  AND p.post_type='our_work'
  AND tt.taxonomy='client_name'

FYI this came up in me trying to answer this question:

http://wordpress.stackexchange.com/questions/1140/

Thanks in advance.

-Mike


More information about the wp-hackers mailing list