Skip to content

Instantly share code, notes, and snippets.

@szbl
Created July 17, 2012 05:10
Show Gist options
  • Save szbl/3127298 to your computer and use it in GitHub Desktop.
Save szbl/3127298 to your computer and use it in GitHub Desktop.
get_terms_for_post_type()
<?php
//
// Assumption: we have two post types, "books" and "videos" and a shared hierarchical taxonomy called "library-section"
//
/*
* Pulls all non-empty terms for a given post type.
*
* @param $taxonomy The name of the taxonomy, e.g. "library-section"
* @param $post_type The name of the post type, e.g. "book"
* @param $parent The parent term_id or slug, defaults to root-level term
* @returns array|false
*/
function get_terms_for_post_type( $taxonomy = 'category', $post_type = 'post', $parent = null )
{
global $wpdb, $wp_taxonomies;
$tax = get_taxonomy( $taxonomy );
if ( is_string( $parent ) )
{
$parent = get_term_by( 'slug', $parent, $taxonomy );
$parent_id = $parent->term_id;
}
else
{
$parent_id = (int) $parent;
}
$parent_str = " AND tax.parent = %d ";
$sql = "
SELECT DISTINCT terms.*
FROM {$wpdb->posts} p, {$wpdb->term_taxonomy} tax, {$wpdb->terms} terms, {$wpdb->term_relationships} rel
WHERE p.post_type = %s
AND p.ID = rel.object_id
AND tax.taxonomy = %s
AND tax.term_id = terms.term_id
AND rel.term_taxonomy_id = tax.term_taxonomy_id
$parent_str
ORDER BY terms.name, terms.slug
";
$sql = $wpdb->prepare( $sql, $post_type, $taxonomy, $parent_id );
return $wpdb->get_results( $sql );
}
// Give me all the sections containing books...
$book_sections = get_terms_for_post_type( 'library-section', 'book' );
foreach ( $book_sections as $section )
{
// do something with the section data
// OR pull it's subsections if you want.
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment