Display taxonomy terms based on custom post type


<?php
    //GET THE POST TYPE OF THE PAGE AND COMPARE IT WITH CUSTOM POST TYPE YOU HAVE CREATED
    if ( 'custom-postType' == get_post_type() )  {
       
        //IF YES THEN ASSIGN CUSTOM TAXONOMY ASSOCIATED WITH THAT CUSTOM POST TYPE
        $taxonomy = 'custom-taxonomy';
       
    } else {
        //ASSIGNING A NULL VALUE WILL RESULT IN 'Invalid taxonomy' WHICH WE LATER WILL REQUIRE TO CHECK
        $taxonomy = "";
    }
?>
<?php
    //GET THE TERMS INSIDE THE 'custom-taxonomy'
    //THIS PURELY FOR VALIDATION. SO THAT IF NOTHING EXSISTS WE NEED NOT DISPLAY ANYTHING.
    $terms = get_terms($taxonomy);
    if(($terms->errors[invalid_taxonomy][0]) != 'Invalid taxonomy') {
?>
       
<?php
    //CREATE AN ARGUMENT WITH THE 'custom-taxonomy' and order it by 'name'
    $args = array(
      'taxonomy'     => $taxonomy,
      'orderby'      => 'name',
      'show_count'   => 0,
      'pad_counts'   => 0,
      'hierarchical' => 1,
      'title_li'     => ''
    );
?>
       
<ul>
    <?php
        //GET THE POST TYPE DISPLAYED IN THE PAGE.
        $post_type =  get_post_type();
    ?>
   
    <?php if(get_post_type()) {  ?>
        <?php
            //iF ANY POST TYPE EXSISTS then do the following
            // DISPLAY AN EXTRA <li> with show all link.
            //THIS IS PURELY FOR AESTHETICAL PURPOSE AND YOU CAN CHOSE TO IGNORE.
        ?>
        <li class="current-cat">
            <a href="<?php bloginfo('url'); ?>/<?php echo $post_type; ?>">Show All</a>
        </li>
    <?php } ?>
   
    <?php
        //DISPLAY THE 'terms' OF THE 'custom-taxonomy' with links.
        wp_list_categories( $args );
    ?>
</ul>

Latest Comments

Leave a Reply

comment on this article