How To Register Menus In WordPress

In a previous snippet we learnt How To Register A Sidebar In WordPress in this snippet we are going to learn how we can easily create custom menus and add them anywhere on your Wordpress blog.

Create A New Wordpress Menu

Wordpress allows you to create your own custom menus from pages or category items. Using your theme settings you can define where certain menus can appear. For example you can create a menu for all your categories and display this at the top of your page. To create a menu in Wordpress go to the menu item in the appearance menu. Pick a name for your menu and start adding items to it. When items are on the menu you can drag and drop the menu items to position them.

Registering Your Menu

To position your newly created menu on your theme you will first need to register a new menu. In your functions.php page copy the following code.

function register_menu() {
	register_nav_menu('primary-menu', __('Primary Menu'));
}
add_action('init', 'register_menu');

The register_nav_menu function requires two parameters the location of the menu and the description.


register_nav_menu( $location, $description );

Displaying The Menu

Where you want to display this menu open the file for example the header.php file and paste the following code.


if ( has_nav_menu( 'primary-menu' ) ) { /* if menu location 'primary-menu' exists then use custom menu */
      wp_nav_menu( array( 'theme_location' => 'primary-menu') ); 
}

The wp_nav_menu function will display a theme menu by providing it with a menu theme location.

Assign Menu

Finally we can assign the primary-menu to your newly created menu. Go back to the menu page in the dashboard find your new menu and assign this menu in your theme location.

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring