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

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 Add, Edit and Delete a Workflow in Etrieve?MiscellaneousHow to list all PHP variables to debug the script?PHPWhat are Null Sessions?Miscellaneous@use rule in SCSS (Sass)SCSSHow to set opacity or transparency using CSS?CSSHow to detect the Blog Page in WordPress?WordPress