bainternet
9/15/2011 - 11:05 PM

Function to get terms only if they have posts by post type

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(); 
}