This code displays a list of child categories of the parent category while a user is on a child category or single post.
The styling around this list is displaying even when a list isn’t being generated. Take a look here where you’ll see an empty black box – I’ve colored it black simply to make it stick out. Not relevant, but this code is impacted by another code in my functions.php.
How do I correctly insert the tags into this code and prevent a list from being generated when no child categories exist?
<?php
$categories = get_the_category();
echo '<ul style="background:#000">';
foreach($categories as $category){
$parent = $category->parent;
if($category->parent == 0){
}
else{
wp_list_categories("child_of=$parent&title_li");
}
echo '';
}
?>
Check that you actually have categories before creating the list, and move the lines that echo the
<ul>
inside the conditional.This will generate multiple lists, not just one.
Here is a version that
echo
es only a single<ul>
.