Clair Smith
Clair Smith

Reputation: 37

Get terms related to custom post type

I am building a site based on categories of information given to each US state. I have created a taxonomy called state_data and a custom post type for each state. The state post types share the taxonomy, but not all states will get all terms. I am looking for a way to list all the terms related only to specific states. The native wp function get_terms gets all the terms for the taxonomy. Is there a way to filter get_terms by post_type?

Upvotes: 0

Views: 2843

Answers (2)

Armstrongest
Armstrongest

Reputation: 15409

You may want to try something like this:

SELECT p.ID, p.post_title, tr.term_taxonomy_id, t.`name` 
FROM wp_term_relationships as tr 
JOIN wp_posts AS p ON p.ID = tr.`object_Id`
JOIN wp_terms AS t ON t.`term_id` = tr.`term_taxonomy_id`
WHERE p.post_type = 'state_data'
AND t.`name` = 'Alabama'
ORDER BY p.ID;

You can select what you want to from the SELECT query... just ID, or whatever fields you wish.

Essentially, what the query is doing is linking up the terms table to the posts table through the terms_relationship table.

Upvotes: 1

david.binda
david.binda

Reputation: 1068

All right thou. If there are not so many entities in each post_type representing state. Say 10 is ok. You can loop for all entities in one post_type and use loop of wp_get_post_terms result to note all term ids and marge it in array.

I'm not so experienced in SQL as I would like to be, but when looking to database, this could be reachable by custom SQL query.

Look, each entity of specific custom post type has unique ID. You can

SELECT ID FROM wp_posts WHERE post_type = 'Alabama';

Now you have all ID's of entities from Alabama. Now you can select all terms assigned to these entities.

SELECT term_taxonomy_id FROM wp_term_relationship WHERE object_id IN ( *RESULT FROM PREVIOUS QUERY* );

So now you've got term_taxonomy_ids related to all Alabama entities and you can get them from wp_term_taxonomy table

SELECT term_id from wp_term_taxonomy WHERE term_taxonomy_id in ( *RESULT FROM PREVIOUS QUERY* );

And finaly, you can get all terms from wp_terms or query them by PHP function. As i said. I'm not SQL expert, so I can not get this together by one SQL query, but I would't be so compliacated to put it all together with a little help of PHP. But what matters is efficiency, I guess...

Upvotes: 2

Related Questions