Add New Menu to WordPress Site Using Code

1. Register a new menu in WordPress admin

Use WordPress’s register_nav_menus to register the menu so it appears in Appearance > Menus > Menu Locations. Place the below PHP code in Code Snippets plugin:

function register_my_menus() {
  register_nav_menus(
    array(
      'header' => __( 'Reid Header Menu' ),
      'other' => __( 'Reid Other Menu' )
     )
   );
 }
 add_action( 'init', 'register_my_menus' );

Important: In the Code Snippet plugin, right below the PHP code, make sure and choose Run snippet everywhere. Otherwise the newly-registered menus will not show up in Appearance > Menus > Menu Locations.

Note: The use of the word Reid in Reid Header Menu in the above PHP is not necessary. It’s just a way for me to see if everything is showing up in the right places.

Source:

2. Display menu in theme header on front-end

Next, use WordPress’s wp_nav_menu () function to display the menu on the front-end of the site. Use theme_location to place the menu in the theme’s header. Since I’m using the Kadence WP theme I need to use an Action Hook to hook the wp_nav_menu into the theme. I’ve chosen the kadence_before_content action hook as an example.

Place the below PHP code in Code Snippets plugin:

/*
 * Display menu in Header using the wp_nav_menu() function
 * https://kinsta.com/blog/wordpress-custom-menu/#3-write-code-to-create-your-custom-wordpress-menu
 * https://www.kadencewp.com/kadence-theme/knowledge-base/advanced/theme-hooks/
 *
 */
function reid_header_menu() {
	wp_nav_menu( array(
		'theme_location' => 'header',
	) );
}
add_action( 'kadence_before_content', 'reid_header_menu' );

In the Code Snippet plugin, right below the PHP code, choose Only run on site front-end (since the menu is only running on the front-end of the site).

Source:

3. Add dropdown for subpages

Will update with new info.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *