Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

php - wordpress, get category names for a custom post type

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; ?>">
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<?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'); ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...