Echo the first category out of an assigned categories array

I have a lot of posts that I need to assign in multiple categories, usually two but sometimes more than two. The assigned categories is a mix of parent/parent and parent/child but never a child/child combination.

I am trying to show the first parent assigned in the meta info.

I’ve wrote the following code, but when I visit a post that has ‘first’ and ‘second’ category assigned to it, the output is including both echos.

Any ideas?

if (is_single() && in_category(‘first’) ) {
$category = get_the_category();
$currentcat = $category[0]->cat_ID;
$currentcatname = $category[0]->cat_name;
$currentcatslug = $category[0]->slug;

if ($currentcatslug == first) {
echo ‘this post in on first category’;
} else {
}
}

if (is_single() && in_category(‘second’) ) {
$category = get_the_category();
$currentcat = $category[0]->cat_ID;
$currentcatname = $category[0]->cat_name;
$currentcatslug = $category[0]->slug;

if ($currentcatslug == second) {
echo ‘this post in on second category’;
} else {
}
}

Read more here:: Echo the first category out of an assigned categories array

Leave a Reply

Your email address will not be published. Required fields are marked *