Skip to content

Instantly share code, notes, and snippets.

@joshsmith01
Forked from bainternet/nocn.php
Created September 24, 2017 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshsmith01/3a84f82c9cda2220a2e5156b7f8e8454 to your computer and use it in GitHub Desktop.
Save joshsmith01/3a84f82c9cda2220a2e5156b7f8e8454 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment