YogeshChauhan . com

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'
  )
);


amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to host Google fonts on your server and add them using CSS?CSSComposing and Extracting Components in ReactReactA complete diagram with building blocks of an Angular applicationAngularIntroduction to components and templates Part 2: Templates and viewsAngularUse inline if to make a shorter conditional syntax in ReactReactHow to Block IPs and User Agents using code in Drupal or WordPress?Drupal