user3383480
user3383480

Reputation: 11

Wordpress: Display only parent category on post loop

How to display only parent category (without child categories) on a post loop?

I have:

<span class="entry-category"><?php the_category(', '); ?></span>

What should I do?

Upvotes: 1

Views: 1520

Answers (2)

H&#252;seyin BABAL
H&#252;seyin BABAL

Reputation: 15550

You can get category and check parent field for each entry like;

<?php
    $categories = get_the_category();
    if($categories){
        foreach($categories as $category) {
            if ($category->parent < 1) {
                // Your action here
            }
        }
    }
?>

Upvotes: 1

Nisarg Patel
Nisarg Patel

Reputation: 260

foreach (get_the_category() as $cat) {  
    $parent = get_category($cat->category_parent);
    if (!get_category($cat->category_parent)) {
        // do something with the category, like use it to create a new query_posts or something
    }
}

Upvotes: 1

Related Questions