Farhan
Farhan

Reputation: 9

How To Add Woocommerce Product Categories To Menu Dynamically?

Is it possible to add a Woocommerce product category to the menu dynamically? How can I do this? I am trying to add woocommerce product category to the menu dynamically. I am expecting a good solution to this problem. I am Unable to do this.

Upvotes: 0

Views: 471

Answers (1)

T Paone
T Paone

Reputation: 493

There are a few ways to do this using the available Wordpress hooks. One such hook you can use is the wp_nav_menu filter (see documentation). This hook allows you to directly modify the output of the nav menu HTML. Be careful, as this will affect all menus unless you set a condition based on the args from the 2nd argument in the filter.

An example implementation

add_filter('wp_nav_menu', 'example_func',10,2);

function example_func(string $nav_menu, $args): string
{
    // Get categories
    $categories = get_categories(['taxonomy' => 'product_cat']);

    //create new unordered list and append to end of navigation.
    $nav_menu .= '<ul>';
    foreach($categories as $cat) {
       $nav_menu .= '<li>' . $cat->name . '</li>'
   }
   $nav_menu .= '</ul>';

return $nav_menu;

If you are wanting to place the products in a specific place, you may be better off looking at creating a custom Nav Walker see docs or changing your filter to a more precise spot.

Upvotes: 1

Related Questions