Yogesh Chauhan's Blog

How to add menu to your WordPress theme?

in WordPress on May 23, 2021

How to Register Menus?

The navigation menu allows you to add different links in the Menu. You can add internal links such as Pages, Posts, Categories, or external links like any website URLs to the menu.

When you are developing a theme, you need to register the menus in order to create a navigation menu. Once it’s registered using a functions.php file, it will appear at Appearance -> Menus.

You can use register_nav_menus() to register the menu.

This code will add two locations, “Primary Menu” and “Secondary Menu”.



function register_theme_menus() {
  register_nav_menus(
    array(
      'primary-menu' => __( 'Primary Menu' ),
      'secondary-menu' => __( 'Secondary Menu' )
     )
   );
 }
 add_action( 'init', 'register_theme_menus' );


A good rule of thumb is to make sure the function doesn’t exist. As you know, in a large functions.php file, it might break your code if the function already exists.

Let’s change the code above slightly:



if ( ! function_exists( 'register_theme_menus' ) ) {
  function register_theme_menus() {
    register_nav_menus(
      array(
        'primary-menu' => __( 'Primary Menu' ),
        'secondary-menu' => __( 'Secondary Menu' )
       )
     );
   }
  add_action( 'init', 'register_theme_menus' );
}


How to Display Menus?

Once you register the menus, you’ll need to add code to display that menu. Use wp_nav_menu() to display the menu at a specific location.

This is how you can add our primary menu, from the code above, to your header.php file.



wp_nav_menu(
  array(
    'theme_location' => 'priimary-menu'
  )
);


How to add a container class with display menu?

All you need to do is pass another argument with a class name.



wp_nav_menu(
  array(
    'theme_location' => 'primary-menu',
    'container_class' => 'primary_menu_class'
  )
);



Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to Display Related Posts in WordPress?WordPressSorting Arrays in JavaScriptJavaScriptAmpersand (Parent Selector) in SCSS (Sass)SCSSHow to switch dark and light themes using pure CSS?CSSHow to overwrite file contents with new content in PHP?PHPbin2hex() and chr() String Functions in PHPPHP