wordpress, get category names for a custom post type

34,013

Solution 1

<?php
$taxonomy = 'filters';
$terms = get_terms($taxonomy);

if ( $terms && !is_wp_error( $terms ) ) :
?>
    <ul>
        <?php foreach ( $terms as $term ) { ?>
            <li><a href="<?php echo get_term_link($term->slug, $taxonomy); ?>"><?php echo $term->name; ?></a></li>
        <?php } ?>
    </ul>
<?php endif;?>

Or in fuctions.php place this:

  function get_the_category_custompost( $id = false, $tcat = 'category' ) {
    $categories = get_the_terms( $id, $tcat );
    if ( ! $categories )
        $categories = array();

    $categories = array_values( $categories );

    foreach ( array_keys( $categories ) as $key ) {
        _make_cat_compat( $categories[$key] );
    }

    return apply_filters( 'get_the_categories', $categories );
}

and call the function as:

<?php $cat = get_the_category_custompost($post->ID, 'Your Custom Taxonomy'); ?>

Solution 2

My answer seems too simple, but I used this to list the categories from a wordpress plugin called DW Question Answer that has separate categories from the standard wp categories.

I am assuming that Design Wall used custom post types to create the q&a part and taxonomies to create the categories.

<ul>
  <?php wp_list_categories('taxonomy=dwqa-question_category&hide_empty=0&orderby=id&title_li=');?>
</ul>
Share:
34,013
Pectus Excavatum
Author by

Pectus Excavatum

Updated on May 24, 2020

Comments

  • Pectus Excavatum
    Pectus Excavatum almost 4 years

    Is there a better way to get the category names for a custom post type in wordpress?

    <?php        // get the portfolio categories
                $terms = get_the_terms( $post->ID, 'filters' );                           
                if ( $terms && ! is_wp_error( $terms ) ) : 
                    $names = array();
                    $slugs = array();
                    foreach ( $terms as $term ) {
                     $names[] = $term->name;
                     $slugs[] =  $term->slug;
                    }                                
                    $name_list = join( " / ", $names );
                    $slug_list = join( " category-", $slugs );
            endif;
        ?>
    
    
        <!-- BEGIN portfolio-item-->
        <li class="portfolio-item third column category-<?php echo $slug_list; ?>" data-filter="category-<?php echo $slug_list; ?>">
    
  • Pectus Excavatum
    Pectus Excavatum over 10 years
    Thanks for the help; much appreciated