Skip to content

Instantly share code, notes, and snippets.

@dalethedeveloper
Created October 2, 2012 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dalethedeveloper/3823530 to your computer and use it in GitHub Desktop.
Save dalethedeveloper/3823530 to your computer and use it in GitHub Desktop.
WordPress fetch custom Taxonomy Terms with Posts
/**
Get all terms in a Taxonomy including associated posts
Like get_objects_in_term() for all terms or get_terms() that includes posts
@$tax string Taxonomy to fetch (Default "post_tag", must be a slug)
@$post_type string Post type to use (Default "post")
@$query_args string Additional Query Args to use when querying objects (Default: '', must be string form, eg 'order=ASC&post_status=published')
@$return_ids bool Return just Post IDs in $return->posts instead of complete post Objects (Default: false)
*/
function get_objects_in_taxonomy($tax = 'post_tag', $post_type = 'post', $query_args = '', $return_ids = false ) {
$tax_types = get_terms($tax);
$post_to_tax = array();
// Reorder terms with slug as index
foreach($tax_types as $key => $tax_type){
$copy = $tax_type; // trust me
if( $return_ids )
$copy->post_ids = get_objects_in_term($tax_type->term_id,$tax);
else {
$copy->posts = array();
foreach($copy->post_ids as $item_id)
$post_to_tax[$item_id] = (string)$tax_type->slug;
}
$tax_types[(string)$tax_type->slug] = $copy;
unset($tax_types[$key]);
}
if( $return_ids )
return $tax_types;
$post_query = new WP_Query('posts_per_page=-1&post_type='.$post_type.' . (empty($query_args) ? '' : '&'.$query_args) );
foreach($post_query->posts as $qpost){
if(!isset($post_to_tax[$qpost->ID]))
continue;
$tax_types[ $post_to_tax[$qpost->ID] ]->posts[] = $qpost;
}
return $tax_types;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment