Insert <ul> Into Sub-child Menu

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.

Read More

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 '';
  }
  ?>

Related posts

1 comment

  1. Check that you actually have categories before creating the list, and move the lines that echo the <ul> inside the conditional.

    $categories = get_the_category();
    if (!empty($categories)) {
      foreach($categories as $category){
        $parent = $category->parent;
        if($parent != 0){
          echo '<ul style="background:#000">';
            wp_list_categories("child_of={$parent}&title_li");
          echo '</ul>';
        }
      }
    }
    

    This will generate multiple lists, not just one.

    Here is a version that echoes only a single <ul>.

    $categories = get_the_category();
    $catli = '';
    if (!empty($categories)) {
      foreach($categories as $category){
        $parent = $category->parent;
        if($category->parent != 0){
          $catli .= wp_list_categories("child_of=$parent&title_li&echo=0");
        }
      }
      if (!empty($catli)) {
        echo '<ul style="background:#000">'.$catli.'</ul>';
      }
    }
    

Comments are closed.