Reputation: 250
I want to exclude top level and 3+ level post categories when viewing a single post. Getting rid of top level is no problem but not sure how i'd go about removing 3+ level. Can anyone shed light on how to deal with this?
This is what I have now:
$categories = get_the_terms( $post->ID, 'category' );
// now you can view your category in array:
// using var_dump( $categories );
// or you can take all with foreach:
foreach( $categories as $category ) {
var_dump($category);
if($category->parent) echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
}
Upvotes: 2
Views: 4131
Reputation: 26150
To get the second level, you'll want to run two loops - one to identify the id's of the top-level, so that you can then identify the categories that have a parent ID that is in the top-level (which means it's a second level).
$categories = get_the_terms( $post->ID, 'category' );
// Set up our array to store our top level ID's
$top_level_ids = [];
// Loop for the sole purpose of figuring out the top_level_ids
foreach( $categories as $category ) {
if( ! $category->parent ) {
$top_level_ids[] = $category->term_id;
}
}
// Now we can loop again, and ONLY output terms who's parent are in the top-level id's (aka, second-level categories)
foreach( $categories as $category ) {
// Only output if the parent_id is a TOP level id
if( in_array( $category->parent_id, $top_level_ids )) {
echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
}
}
Upvotes: 4