Skip to content

Instantly share code, notes, and snippets.

@bainternet
Created September 15, 2011 23:05
Show Gist options
  • Save bainternet/1220740 to your computer and use it in GitHub Desktop.
Save bainternet/1220740 to your computer and use it in GitHub Desktop.
Function to get terms only if they have posts by post type
<?php
/**
* Function to get terms only if they have posts by post type
* @param $taxonomy (string) taxonomy name eg: 'post_tag','category'(default),'custom taxonomy'
* @param $post_type (string) post type name eg: 'post'(default),'page','custom post type'
*
*
* Usage:
* list_terms_by_post_type('post_tag','custom_post_type_name');
**/
function list_terms_by_post_type($taxonomy = 'category',$post_type = 'post'){
//get a list of all post of your type
$args = array(
'posts_per_page' => -1,
'post_type' => $post_type
);
$terms= array();
$posts = get_posts($args);
foreach($posts as $p){
//get all terms of your taxonomy for each type
$ts = wp_get_object_terms($p->ID,$taxonomy);
foreach ( $ts as $t ) {
if (!in_array($t,$terms)){ //only add this term if its not there yet
$terms[] = $t;
}
}
}
//when you get here $terms is an array of term objects that have posts of your custom type
//so just print them out.
echo '<ul>';
foreach($terms as $tr){
echo '<li><a href="'.get_term_link($tr->slug, $taxonomy).'">'.$tr->name.'</a></li>';
}
echo '</ul>';
wp_reset_postdata();
}
@bakaburg1
Copy link

There should be a way to do this without cycling through all the posts!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment