dungey_140
dungey_140

Reputation: 2802

WordPress Individual Category Name within wp_query

Using the below wp_query to pull in the latest post from three different categories. As part of this I want to display the category name appropriate for each article, which the_category(); does achieve, however it places a <a> and <li> tags around the name. I'm wanting to simply get the name of the category?

<?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();
?>

Upvotes: 0

Views: 1679

Answers (1)

Raunak Gupta
Raunak Gupta

Reputation: 10809

You can use get_the_category() to get the category linked to that post.

Replace this

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

with this

<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() echo containing by it self so you don't need to echo it.

Hope this helps!

Upvotes: 1

Related Questions