仅从特定自定义帖子类型中获取类别

时间:2016-04-16 00:46:23

标签: php wordpress custom-post-type

我正在尝试从特定帖子类型中获取类别:member

我正在使用此代码

<?php
    $taxonomy = 'category';
    $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>

但问题是:当我向member添加类别时,它也会添加到post type : post,当删除时,它也会从两种帖子类型中删除。 我现在能做什么?

1 个答案:

答案 0 :(得分:0)

尝试这种方式,这将显示特定帖子的类别,并检索帖子的条款。

<?php
$postArg = array('post_type'=>'post',
                        'posts_per_page'=>-1,
                        'order'=>'desc',
                      );

        $getPost = new wp_query($postArg);
        global $post;
        if($getPost->have_posts()){
            echo '<ul>';
                while ( $getPost->have_posts()):$getPost->the_post();

                    echo "<h2>".$post->post_title."</h2>";
                    $terms = get_the_terms($post->ID, 'category' );
                    foreach ($terms as $term) {
                        echo "<li>".$term_name = $term->name.'</li>';
                    }
                endwhile;
            echo '</ul>';
        }

?>

第二种方式

<?php 

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

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