Skip to content

Instantly share code, notes, and snippets.

@joshsmith01
Forked from bainternet/nocn.php
Created September 24, 2017 04:43
Show Gist options
  • Save joshsmith01/3a84f82c9cda2220a2e5156b7f8e8454 to your computer and use it in GitHub Desktop.
Save joshsmith01/3a84f82c9cda2220a2e5156b7f8e8454 to your computer and use it in GitHub Desktop.

Revisions

  1. @bainternet bainternet revised this gist Sep 15, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion nocn.php
    Original file line number Diff line number Diff line change
    @@ -7,7 +7,7 @@
    *
    *
    * Usage:
    * list_terms_by_post_type('post_tag','castom_post_type_name');
    * list_terms_by_post_type('post_tag','custom_post_type_name');
    **/


  2. @bainternet bainternet created this gist Sep 15, 2011.
    41 changes: 41 additions & 0 deletions nocn.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    <?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','castom_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();
    }