When I was creating a WordPress theme for my client I needed to get dropdown of Navigation menus in customize so user can choose a menu. I wrote a function for that which really worked well. You can use it if you need it.
Add it these below codes in your themes function.php file. It creates the dropdown.
/**
* Dropdown Menu List for customizer
*/
if ( !function_exists( 'your_theme_customizer_menulist' ) ) {
// Function
function your_theme_customizer_menulist() {
$menus = wp_get_nav_menus();
$menu_list['none'] = esc_html__(' -- Choose Menu -- ', 'your-theme');
foreach ($menus as $menu) {
$menu_list[$menu->slug] = $menu->name;
}
return $menu_list;
}
}
Explanation of the above code:
Set a variable $menu to get all available menus, then set an another variable $menu_list to store the dropdown value. Now do a foreach loop to exact the menus into drowdown options.
Add the below code in function.php to create setting in customize.
/**
* Register customizer
*/
if ( !function_exists( 'your_theme_customize_register' ) ) {
// Function starts
function your_theme_customize_register( $wp_customize ) {
/** Header Options Panel */
$wp_customize->add_panel( 'your_theme_header_settings', array(
'title' => esc_html__( 'Header Settings', 'your-theme' ),
'description' => esc_html__( 'Configure header settings', 'your-theme' ),
'priority' => 10,
));
/** Top Header Options */
$wp_customize->add_section( 'your_theme_top_header_options', array(
'title' => esc_html__( 'Top Header', 'your-theme' ),
'panel' => 'your_theme_header_settings',
));
$wp_customize->add_setting('your_theme_top_navigation_menu', array(
'sanitize_callback' => 'sanitize_option',
'default' => 'none',
'transport' => 'refresh'
));
$wp_customize->add_control('your_theme_top_navigation_menu', array(
'section' => 'your_theme_top_header_options',
'type' => 'select',
'label' => esc_html__('Select Menu', 'your-theme'),
'choices' => your_theme_customizer_menulist() // Dropdown function which we created first
));
}
add_action( 'customize_register', 'your_theme_customize_register' );
}
Explanation of the above code: The above code creates customize panel, section and settings. Customize settings will look like below image.
How to use the code in front end
/**
* Echo navigational menu
*/
$top_menu = get_theme_mod( 'your_theme_top_navigation_menu' );
//Ignore if menu is empty
if ( !empty( $top_menu ) ) {
wp_nav_menu( array(
'menu' => $top_menu,
'menu_id' => 'menu',
'items_wrap' => '<ul id="menu" class="%2$s">%3$s</ul>',
) ) ;
}
It will echo the navigational menu, place it in header.php or wherever you want to display the menu. Please feel free to reply if you have any questions. Thank you!
May 29, 2020
Aug 03, 2023
Aug 15, 2019
Aug 05, 2024
Sep 17, 2024
Sep 17, 2024
Aug 05, 2024
Aug 03, 2023
May 29, 2020
Aug 15, 2019