Monday, 26 August 2013

Listing terms used by a custom post type (the taxonomy is shared across multiple CPT)

Listing terms used by a custom post type (the taxonomy is shared across
multiple CPT)

I have multiple custom post types and they share some custom taxonomies. I
want to a (hierarchy format) drop down of only the terms used by a
specific custom post type - the drop down will be the filter for the
archive-post-type.php page.
CPTs: Winery, Wines, plus others (but not relevant)
Taxonomies: Regions, Wine Types, plus others (but not relevant)
Wineries will not exist in all regions that wines do - but when listing
the terms it shows all of them. I need to hide any terms that are not
being used by the Winery custom post type.
The output would be a url in the format
http://website.com/winery-profiles/?regions=victoria (which works) just
need to get the list of terms ONLY used by the winery CPT
Any help would be appreciated!
Here is where i'm at:
function get_terms_by_cpt($taxonomy, $post_types=array() ){ global $wpdb;
$post_types=(array) $post_types;
$key = 'wpse_terms'.md5($taxonomy.serialize($post_types));
$results = wp_cache_get($key);
if ( false === $results ) {
$where =" WHERE 1=1";
if( !empty($post_types) ){
$post_types_str = implode(',',$post_types);
$where.= $wpdb->prepare(" AND p.post_type IN(%s)", $post_types_str);
}
$where .= $wpdb->prepare(" AND tt.taxonomy = %s",$taxonomy);
$query = "
SELECT t.*
FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id =
tt.term_taxonomy_id
INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
$where
GROUP BY t.term_id";
$results = $wpdb->get_results( $query );
wp_cache_set( $key, $results );
}
return $results;
But I can't get it to output the terms in their hierarchy (which i need
for the select list). I've tried grouping by tt.parent_id but then it only
returns one of the terms (and it's children) and i know i have selected
more.
Help?

No comments:

Post a Comment