Skip to content

Instantly share code, notes, and snippets.

@unfulvio
Created March 6, 2014 02:27
Show Gist options
  • Save unfulvio/9381073 to your computer and use it in GitHub Desktop.
Save unfulvio/9381073 to your computer and use it in GitHub Desktop.
WordPress: get only terms connected to posts of a specified type
<?php
/**
* Get Terms used by Post Type
* Fetches only terms actually used by posts of a specified post type
*
* @param string $taxonomy the taxonomy to look for terms
* @param string $post_type the post type to match the taxonomy terms found
*
* @return array the query result (an array of taxonomy terms as objects)
*/
function get_terms_by_post_type( $taxonomy, $post_type ) {
global $wpdb;
$query = $wpdb->get_results(
"SELECT t.*, COUNT(*) 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 p.post_type IN('" . $post_type . "') AND tt.taxonomy IN('" . $taxonomy . "') GROUP BY t.term_id"
);
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment