I'm trying to highlight list items that belong to the same category as that of the current category page.
For an example, I have a category called food, with the subcategories: breakfast, lunch and dinner. If you navigate to the sub-category lunch – in a loop that calls all posts regardless of category – I want all list items that are associated to lunch, to be highlighted.
Firstly I use get_category
and ->term_id
to define the ID of the category we're currently on. Secondly, in the loop, I use get_the_category
and [0]->cat_ID
to retrieve the ID (but only the first in the array) of each individual list item. Lastly, I use in_array
to see if there is a match between the two arguments, and if so echo a value.
My problems lies in the $categories[0]->cat_ID
. If a list item is associated to more than one category, retrieving only the first one in the array is no good.
How do I create an argument that will output all category IDs associated with a list item in a loop?
<?php
$thisTrueCat = get_category( get_query_var( 'cat' ) );
?>
<!-- loop start -->
<?php
$categories = get_the_category();
$categories_id = $categories[0]->cat_ID;
?>
<?php if( in_array( $thisTrueCat->term_id, array($categories_id) ) ) { echo 'cat-hi'; }?>