Skip to content

Instantly share code, notes, and snippets.

@steve10287
Last active November 14, 2022 11:51
Show Gist options
  • Save steve10287/d5d765505295c223e80f5051192fc014 to your computer and use it in GitHub Desktop.
Save steve10287/d5d765505295c223e80f5051192fc014 to your computer and use it in GitHub Desktop.
Wordpress - Category Sub Menu Walker
class Walker_Add_Myterms extends Walker_Nav_Menu
{
public function end_el(&$output, $item, $depth = 1, $args = array())
{
if ($item->object === 'category') {
$children = get_terms('category', array('child_of' => $item->object_id));
if (!empty($children) && !is_wp_error($children)) {
$output .= '<ul class="sub-menu">';
if (isset($children) && !is_wp_error($children) && sizeof($children) > 0) {
$child_items = '';
foreach ($children as $child) {
$child_term = get_term($child, 'category');
$child_item = '<li id="term-item-' . $child_term->term_id . '" class="menu-item menu-item-type-taxonomy menu-item-object-category term-item-' . $child_term->term_id . '"><div class="ancestor-wrapper">';
$child_item .= '<a href="' . get_term_link($child_term, 'category') . '">' . $child_term->name . '</a>';
$child_item .= '</div></li>';
$child_items .= $child_item;
}
$output .= $child_items;
}
$output .= '</ul>';
}
}
$output .= "</li>\n";
}
}
@steve10287
Copy link
Author

steve10287 commented Nov 14, 2022

Add this to your functions.php and then call the walker like this:

<nav>
	<?php
	wp_nav_menu(array(
		'theme_location' => 'main_menu',
		'menu_id'        => 'main_menu',
		'container' => false,
		'walker' => new Walker_Add_Myterms(),
	));
	?>
</nav>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment