Create a Space theme for WordPress – 2021 – Part 5, Navigation

Introduction – add a CSS folder and main .css file

In this tutorial, we add a navigation bar to the header. First, create a folder named CSS, in the space theme folder, then create a file named main.css. This file will contain the styling for the menu.

Next, the file needs to be enqueued so that a link to it is placed in the header. Add the code below to the load_css() function in functions.php, make sure that it is below the Bootstrap enqueue function.

wp_register_style('main', get_template_directory_uri() . '/css/main.css', array(),false, 'all');
    wp_enqueue_style('main');

Procedure summary – Add a nav menu

1/ Add a menu location to the header file
2/ Register the location in the functions file.
3/ Style the menu in main.css

Add a menu location

To add a menu you need to add a menu location to the header file. Use the function wp_nav_menu() function. This has two parameters, in an array, the name of the registered theme location and an added CSS class. The top-bar class is added to the unordered list element that forms the WordPress menu.

<header>
 <div class="container">
  <?php 
  // nav area
   wp_nav_menu(
    array(
        'theme_location' => 'top-menu',
        'menu_class'=> 'top-bar'
     )
   )
   ?>
  </div>
</header>

Register the menu location in functions.php

In order for the menu system to show up in the backend, you need to add theme support for them in functions.php. Once this is done use the register_nav_menus() function to register the location name and handle. Here we are also registering a mobile menu location.

// Theme options
add_theme_support('menus');

//menus

register_nav_menus(
    array(
        'top-menu' => 'Top menu Location',
        'mobile-menu' => 'Mobile menu Location'
    )
)
?>

Style the menu

Now it’s time to style the menu using the main.css file we added earlier.