WordPress Display Different Navigation Menu By Category – WordPress Tutorial

By | October 8, 2024

Usually, we can create a wordpress navigation menu easily in wordpress. For example:

wordpress create navigation menu

However, if we want to display different navigation menu based on post category, how to do?

In this tutorial, we will discuss this topic.

1. Get wordpress category name

First, we should get post category name.

Here is an example code:

if(is_single()){
    $categories = get_the_category();
    var_dump($categories );
}

Run this code, we may get:

array(1) {
  [0]=>
  object(WP_Term)#1553 (17) {
    ["term_id"]=>
    int(58)
    ["name"]=>
    string(5) "Cat 1"
    ["slug"]=>
    string(5) "cat-1"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(58)
    ["taxonomy"]=>
    string(8) "category"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    int(0)
    ["count"]=>
    int(1)
    ["filter"]=>
    string(3) "raw"
    ["term_order"]=>
    string(1) "4"
    ["cat_ID"]=>
    int(58)
    ["category_count"]=>
    int(1)
    ["category_description"]=>
    string(0) ""
    ["cat_name"]=>
    string(5) "Cat 1"
    ["category_nicename"]=>
    string(5) "cat-1"
    ["category_parent"]=>
    int(0)
  }
}

Then, we can code below to get the final category name.

if ( ! empty( $categories ) ) {
    echo esc_html( $categories[0]->name );	
}

To get more wordpress category information, you can read:

WordPress get_term_by(): Get Category and Post Tag by Slug

WordPress Beginner’s Guide to Get Category Information in category.php

2. Get all your created menus

You may have created some menus in wordpress. To get all menus, you can use code below:

$defaults = array(
	'name'       => 'python_nav',
        'taxonomy'   => 'nav_menu',
        'hide_empty' => false,
        'orderby'    => 'name',
        );
$all_menus = wp_get_nav_menus($defaults);

In this code, we will get menu named “python_nav“.

In order to display different navigation menu based on categroy, we can use category name to filter menus that we have created.

For example:

If the category name = “python

Then, we can create a menu named “python_nav

Finaly, we can get “python_nav” menu based on category name.

3. Display navigation menu

We have got a created navigation menu based on category name, then, we can display it.

We can use this code.

if(count($all_menus) > 0){
    wp_nav_menu( array( 'menu' => $all_menus[0], 'menu_id' => 'primary-menu', 'menu_class' => 'sf-menu' ) );
} else if ( has_nav_menu( 'primary' ) ) {
    wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu', 'menu_class' => 'sf-menu' ) );
}

In this example, we will use wp_nav_menu() function to display navigation menu. $all_menus[0] will be displayed.

Leave a Reply