簡體   English   中英

僅獲取特定自定義帖子類型的類別

[英]Get only categories from a specific 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並且在刪除時也會從兩種帖子類型中刪除。 我現在能做什么?

嘗試這種方式,這將顯示特定帖子的類別並檢索帖子的術語。

<?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>'; 
 }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM