2017-03-27 3 views
0

以下のwp_queryを使用して、最新の投稿を3つの異なるカテゴリから引き出します。これの一部として、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()を使用することができます。

はFYIこの

<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> 

でこれ

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

を交換してください:the_category()は、あなたがそれをエコーする必要はありませんので、それは自己によって含むエコー。

+0

完璧!ありがとうRaunak。この答えを正しいとマークし、質問をアップアップすることも自由です。 –

関連する問題