I'm trying to build an automated mega menu that loops through all product-category terms and displays them in a hierarchical underscored list, as well as including post in each term.

For example, let's say these are my terms:

  • Utensils
    • Paints
    • Crayons
    • Markers
  • Canvases
    • Cloth
      • Canvas
      • Felt
    • Paper

And any of those terms could have posts associated with them. I need to display the terms in that same order, with their posts listed as children of the relevant term. So, it would end up looking something like this:

  • Utensils (product-category)
    • Paints (product-category)
      • Oil Paints (product)
      • Acrylic Paints (product)
    • Crayons (product-category)
      • Crayola (product)
    • Markers (product-category)
      • Crayola (product)
      • Sharpie (product)
  • Canvases (product-category)
    • Awesome Canvas™ (product)
    • Cloth (product-category)
      • Canvas (product-category)
        • Flexible (product)
      • Felt (product-category)
    • Paper (product-category)

(I'm bad at making examples)

Now, I can loop through the top level terms, but I'm having a hard time making a while loop that goes all the way down until the next term has no children.

Here's what I have so far:

$terms = get_terms("product-category", array(
    "parent" => 0,

if ($terms) {
    $output = "<ul class='menu-list sub-menu'>";

    foreach ($terms as $term) {

        $output .= "<li class='menu-item'>";

        $output .= "<a href='#'>\$term = {$term->name}</a>";

         * Here's where things get weird. I need to figure out a way to
         * loop through all child categories and dislpay them in an
         * unordered list, while also including their own child posts.

        $output .= "</li>";

    $output .= "</ul>";

I've scrapped it several times and started over. I'll keep updating this as I make progress.

Edit 1: The goal is to essentially combine something like wp_list_categories with the categories posts.

Edit 2: New idea is to abstract the function to get children in to it's own function. Trying this now...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.