Adding a customizable menu to your WordPress theme

Tiempo de lectura: 2 minutos
Continuing from the previous post on creating a WordPress theme (https://devcodelight.com/?p=6987), now we’re going to add a customizable menu.

To do this, we’ll go to header.php and add the following:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php wp_title(); ?></title>
    <?php wp_head(); ?>
</head>
<nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
    <div class="container">
        <a class="navbar-brand" href="<?php echo home_url(); ?>"><?php bloginfo('name'); ?></a>
        <?php
        wp_nav_menu(array(
            'theme_location' => 'main-menu',
            'menu_class' => 'navbar-nav ml-auto',
            'container' => false,
        ));
        ?>
    </div>
</nav>
<body <?php body_class(); ?>>

We have created the menu called main-menu:

<nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
    <div class="container">
        <a class="navbar-brand" href="<?php echo home_url(); ?>"><?php bloginfo('name'); ?></a>
        <?php
        wp_nav_menu(array(
            'theme_location' => 'main-menu',
            'menu_class' => 'navbar-nav ml-auto',
            'container' => false,
        ));
        ?>
    </div>
</nav>

And it will also allow us to customize it from WordPress itself.

Now let’s add the action that will allow us to customize it. Let’s go to functions.php and add:

function register_menus() {
    register_nav_menu('main-menu', 'Main Menu');
}
add_action('after_setup_theme', 'register_menus');

And now, we’ll be able to customize our menu:

We can enhance the menu design with CSS

Leave a Comment