Wordpress: register_my_menus / creating a new menu does not work

Viewed 92

I have prepared a positioning of my own menus. So far the menu only reacts to the styling. Wordpress simply selects any menu. For example, if I create a new footer menu, the actual top menu is replaced. The current solution without further menus:

<?php wp_nav_menu( [ 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?> 

The code in the function.php I have used so far:

function register_my_menus() {

  register_nav_menus(

   array( 'top_menu' => __( 'Top Menu', 'test' ),

          'footer_menu' => __( 'Footer Menu', 'test' ))

          'blog_menu' => __( 'Blog Menu', 'test' ))

  );

}

add_action ('init', 'register_my_menus');

The code in the header.php that I have tried so far for positioning:

<?php wp_nav_menu( array( 'theme_location' => 'top_menu', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown' ) ); ?>

2 Answers

I love the object-oriented approach:

class Menu_init {

    public function __construct() {
        add_action( 'init', array($this, 'register_menus'));
    }

    public function register_menus() {

        register_nav_menus(

            array(
                'top_menu' => __( 'Top Menu', 'test' ),
                'footer_menu' => __( 'Footer Menu', 'test' )
                'blog_menu' => __( 'Blog Menu', 'test' )
            )

        );

    }
    
}

new Menu_init();

and for your header of course:

<?php 
wp_nav_menu( [ 
    'theme_location' => 'primary', 
    'container_id' => 'main-nav',
    'menu_id' => 'menu-top-menu', 
    'menu_class' => 'dropdown'
] );
?>

It is true, you have an extra bracket ( ) ).

function register_my_menus() {

    $locations = array(
        'primary'  => __( 'Top Menu', 'test' ),
        'blog' => __( 'Blog Menu', 'test' ),
        'footer'   => __( 'Footer Menu', 'test' ),
    );

    register_nav_menus( $locations );
}

add_action( 'init', 'register_my_menus' );
<?php wp_nav_menu( [ 'theme_location' => 'primary', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?> 
Related