Get all categories of a custom post type

房东的猫 提交于 2019-12-01 23:27:59

问题


I am trying to get all categories of a custom post type.I am using get_the_category(); function to retrieve the categories.But if i have 3 posts with 1 category the category is repeated 3 times :o .

My codes are

<?php 
    query_posts( array( 'post_type' => 'member', 'showposts' => 8 ) );
    if ( have_posts() ) : while ( have_posts() ) : the_post();
        $categories = get_the_category();
            foreach ( $categories as $category ) { 
        echo $category->name, ' '; 
    }             
?>
<?php endwhile; endif; wp_reset_query(); ?>

Is there any solutions??


回答1:


Try this way get only category of custom post

<?php 

$category = get_terms('category');//custom category name 

foreach ($category as $catVal) {
    echo '<h2>'.$catVal->name.'</h2>'; 
 }
?>



回答2:


you can find more info from Here REFERENCE FOR get_terms

<?php
$taxonomy = 'YOUR TEXONOMY NAME';
$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;?>



回答3:


You're looping through posts, did you try this?

<?php
wp_list_categories( array(
    'taxonomy' => 'category', // CHANGE HERE TO YOUR TAXONOMY
) );
?>

More info here: https://developer.wordpress.org/reference/functions/wp_list_categories/



来源:https://stackoverflow.com/questions/36615440/get-all-categories-of-a-custom-post-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!