Created
October 2, 2012 21:48
-
-
Save dalethedeveloper/3823530 to your computer and use it in GitHub Desktop.
WordPress fetch custom Taxonomy Terms with Posts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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