Skip to content

Instantly share code, notes, and snippets.

@westcoastdigital
Created May 15, 2019 13:56
Show Gist options
  • Save westcoastdigital/e4ad774dbc65125444c272dcf68c4b2e to your computer and use it in GitHub Desktop.
Save westcoastdigital/e4ad774dbc65125444c272dcf68c4b2e to your computer and use it in GitHub Desktop.
Dynamically add WooCommerce product categories to primary menu
<?php
function gp_add_woo_categories_to_menu($items, $args)
{
if ($args->theme_location == 'primary') {
$cat_args = array(
'orderby' => 'name',
'order' => 'asc',
'hide_empty' => true,
);
$product_categories = get_terms('product_cat', $cat_args);
$menu_item = '<li class="menu-item">';
$menu_item .= '<a>' . __('Categories', 'generatepress') . '</a>';
$menu_item .= '<ul class="sub-menu">';
foreach ($product_categories as $category) {
$menu_item .= '<li class="menu-item">';
$menu_item .= '<a href="' . get_category_link($category->term_id) . '">';
$menu_item .= $category->name;
$menu_item .= '</a>';
$menu_item .= '</li>';
}
$menu_item .= '</ul>';
$menu_item .= '</li>';
$items .= $menu_item;
}
return $items;
}
add_filter('wp_nav_menu_items', 'gp_add_woo_categories_to_menu', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment