How to create a custom navigation menu in WordPress using wp_nav_menu

The WordPress wp_nav_menu function is used to display a navigation menu on a WordPress website. It allows users to easily create and manage custom menus through the WordPress dashboard and then display them on their site using this function.

This function can be useful for website owners who want to have control over the structure and content of their navigation menus. It provides a way to create custom menus that can include pages, categories, custom links, and more, and then display them in various locations on the website, such as the header, footer, or sidebar.

The wp_nav_menu function provides a flexible and user-friendly way to manage and display navigation menus on a WordPress website.

Parameters Accepted by wp_nav_menu Function

  • $args (array, optional. Default value: array()): Array of nav menu arguments

Value Returned by wp_nav_menu Function

The function returns either void, string, or false. It returns void if the ‘echo’ argument is set to true, and it returns the menu output if ‘echo’ is false. If there are no items or no menu was found, the function returns false.

Examples

How to display a simple menu using wp_nav_menu

Below is an example of how to display a simple menu using the wp_nav_menu function:

<?php
 wp_nav_menu(array('theme_location' => 'primary'));
?>

This code snippet uses the wp_nav_menu function to display a menu assigned to the ‘primary’ theme location.

How to display a menu with custom parameters using wp_nav_menu

Below is an example of how to display a menu with custom parameters using the wp_nav_menu function:

<?php
 wp_nav_menu(array(
 'theme_location' => 'primary',
 'menu_class' => 'custom-menu-class',
 'container' => 'nav'
 ));
?>

This code snippet uses the wp_nav_menu function to display a menu assigned to the ‘primary’ theme location, with custom CSS class and container specified.

How to display a fallback menu using wp_nav_menu

Below is an example of how to display a fallback menu using the wp_nav_menu function:

<?php
 wp_nav_menu(array(
 'theme_location' => 'primary',
 'fallback_cb' => 'wp_page_menu'
 ));
?>

This code snippet uses the wp_nav_menu function to display a menu assigned to the ‘primary’ theme location, with a fallback to the wp_page_menu function if no menu is assigned.

Conclusion

The wp_nav_menu function is an useful component for creating and displaying navigation menus in WordPress. It provides a flexible and customizable way to control the appearance and functionality of menus on a website. By understanding the various parameters and options available, developers can create dynamic and user-friendly navigation systems that enhance the overall user experience. With its extensive documentation and support within the WordPress community, the wp_nav_menu function is a valuable resource for any WordPress developer looking to streamline their menu creation process.

Related WordPress Functions