2017-03-27 54 views
0

使用下面的wp_query從三個不同的類別中提取最新的帖子。作爲其中的一部分,我希望顯示適合每篇文章的類別名稱,其中the_category();確實可以實現,但它在名稱周圍放置了一個<a><li>標籤。我想簡單地得到類別的名稱?wp_query中的WordPress個人類別名稱

<?php 
$categories = get_categories(); 
foreach ($categories as $category) 
{ 

} 
$args = array(
    'cat' => 'article,fitness,recipe', 
    'posts_per_page' => '3', 
); 

$query = new WP_Query($args); 

if ($query->have_posts()) 
{ 

    ?> 
    <?php 
    while ($query->have_posts()) 
    { 
     $query->the_post(); 
     ?> 
     <article id="post-<?php the_ID(); ?>" class="col"> 
      <h5><?php echo the_category(); ?></h5> 
     </article> 

    <?php } // end while ?> 
<?php 
} // end if 
wp_reset_postdata(); 
?> 

回答

1

您可以使用get_the_category()獲得鏈接到 那個帖子的類別。

替換此

<article id="post-<?php the_ID(); ?>" class="col"> 
    <h5><?php echo the_category(); ?></h5> 
</article> 

與此

<article id="post-<?php the_ID(); ?>" class="col"> 
    <?php 
    $category_detail = get_the_category(get_the_ID()); 
    $cat_arr = []; 
    foreach ($category_detail as $cd) 
    { 
     $cat_arr[] = $cd->cat_name; 
    } 
    ?> 
    <h5><?= !empty($cat_arr) ? implode(', ', $cat_arr) : 'N/A'; ?></h5> 
</article> 

FYI:the_category()回聲含有它的自我,所以你不需要它呼應。

希望這會有所幫助!

+0

完美!謝謝Raunak。將這個答案標記爲正確的,也可以提出問題! –

相關問題