How to Build a WordPress Starter Theme: Part 5 – Menus and Sidebars

0

Welcome to Part 5 of “How to Build a WordPress Starter Theme”. In the previous part of the series, we started working in the functions.php file. We looked at using functions to easily inject code and features into our theme using hooks, actions and filters. In this part, we’ll continue working in the functions.php file and add the WordPress menu functionality and also register widgetised sidebars. To do this, we’ll also need to add some template tags to our index.php file. Let’s get started!

Adding Theme Support: Menus

If you login to your WordPress install, you’ll notice under Appearance there are no links for either Menus or Widgets. To get these to show up, we need to add this functionality to our theme. This is a two-step process. First, we register theme support in functions.php. Then we use WordPress template tags to tell WordPress where exactly in our theme files we want to have these displayed. So, let’s add the menu functionality first.

Open up functions.php in your text editor, and at the bottom, add the following function:

function noesis_register_nav_menus() {
  /**
   * Register Nav Menu
   */
  register_nav_menu( 'header-menu', __( 'Header Menu' ) ); // Register menu location in admin and localise name
}
add_action( 'init', 'noesis_register_nav_menus' );

Let’s break it down. For now we’re only registering one menu in our header. For this reason, I’ve decided to use register_nav_menu(), instead of register_nav_menus(), which allows for the creation of multiple menus using an array. You can use register_nav_menus() or simply repeat register_nav_menu() for each new menu you wish to register. Both register_nav_menus() and register_nav_menu() take two parameters:

  • Location: The first parameter of regsiter_nav_menu() is the $location. In truth, this is better described as $location_slug or even $menu_id. You can call this whatever you like, as long as it’s unique for this menu. Knowing that this menu is explicitly for the header, I’ve named it 'header-menu'.
  • Description: The second parameter is $description. Again, this is slightly misleading. In truth, this is what you’ll see when viewing your menu from the dashboard. It would be better descriped as $display_text. I’ve called it 'Header Menu', and wrapped it in our localisation function to allow for translation support. Remember, anything output from a function which will be readble by the user from the dashboard or end user should be localised.

Once the function is ready, we call it with our add_action() function, and tell it we want this to happen on init. In other words, when WordPress renders our markup.

To read more on registering menu support, visit the Codex page, Navigation Menus. From there, you’ll find all the necessary links.

Adding Template Tags: Menus

The next step is to add our template tag to our theme where we want the 'header-menu' to be displayed. Open index.php and find the nav section:

<!-- PRIMARY MENU -->
<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Blog</a></li>
  </ul>
</nav>

Now, go ahead and replace it with our template tag, wp_nav_menu():

<nav>
<?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); // Display the user-defined menu in Appearance > Menus ?>
</nav>

Let’s take a closer look at the wp_nav_menu() template tag. The function accepts one argument in the form of an associative array. Each of the key => value pairs within the array are optional, however, if you do not give a 'theme_location', the menu will fallback to simply displaying all pages created in the menu.

This is the same as using wp_page_menu(), which is the default menu behaviour. The 'theme_location' value is the $location parameter defined in our regsiter_nav_menu() function. Rather than going through each option here, I’ll simply direct you to the Codex page, wp_nav_menu().

Once you start to style your theme, you’ll most likely use the various _class, _id, _before, _after, and _wrap options in particular.

Adding Theme Support: Sidebars

So, registering sidebars is done in a similar fashion to menus. You register them in your functions.php file, and then tell WordPress where in your template files you want it to be available. I use the word available because, unlike menus, you may want your sidebar to remain hidden under certain circumstances, such as when no widgets are placed in that sidebar. Let’s register our sidebar.

In functions.php, include the following:

/**
 * Register and Widgetize Sidebars
 *
 */
function noesis_widgets_init() {
  /**
   * Right Sidebar
   *
   */
  register_sidebar( array(
    'name' => __( 'Right Sidebar', 'noesis' ), // Sidebar name (default is localized 'Sidebar' and numeric ID).
    'id' => 'noesis-right-sidebar',            // Sidebar id - Must be all in lowercase, with no spaces (default is a numeric auto-incremented ID).
    'description' => __( 'Right-hand Sidebar of the Noesis Theme', 'noesis' ), // Text description of what/where the sidebar is. Shown on widget management screen. (default: empty)
    'class' => '', // CSS class anem to assign to widget HTML (Default: empty)
    'before_widget' => '<li id="%1$s">',       // HTML to be placed before every widget (default: <li id="%1$n">) Uses sprintf for variable substitution
    'after_widget' => '</li>',                 // HTML to be placed after every widget
    'before_title' => '<h3>',                  // HTML to be placed before every title
    'after_title' => '</h3>'                   // HTML to be placed after every title
  ) );
}
add_action( 'widgets_init', 'noesis_widgets_init' );

Here, we are creating a sidebar using the register_sidebar() function. The register_sidebar() function accepts an array of arguments. The comments above will outline what each does. Again, take note that anywhere the text would be visible to the user I’ve wrapped in the localisation functions, along with the theme’s textdomain. Also, %1$s allows WordPress to automatically generate the id attribute in the HTML based on the specified id of the sidebar.

There is a register_sidebars() function which allows you to register multiple sidebars in one go. However, it is recommended to instead use register_sidebar() multiple times, because it allows you to assign a unique name to each sidebar, such as Right Sidebar or Left Sidebar. Although these names only appear in the admin interface, it is a best practice to name each sidebar specifically, giving the user some idea as to the context for which each sidebar is meant to be used.

Once we’ve created our function, we use the widgets_init hook to tell WordPress to run this when the widgets are generated.

Adding Template Tags: Sidebar

Finally, we’ll open our index.php file and find the <aside> section.

<!-- SIDEBAR -->
<aside>
  <p>This is the sidebar</p>
</aside>

Go ahead and replace it with the following:

<?php
  // Check of the given sidebar has any widgets (is in use/is active)
  if( is_active_sidebar( 'noesis-right-sidebar' ) ) :
?>

<aside>
  <?php dynamic_sidebar( 'noesis-right-sidebar' ); ?>
</aside>

<?php endif; ?>

So, first we check if the sidebar is in use using the conditional tag, is_sidebar_active( $index ). Simply put, this checks if the sidebar has widgets within it and if so, returns true, and we display our aside markup and our sidebar. If it doesn’t, it returns false and we display no markup here. The is_sidebar_active() conditional tag requires the name or id as its $index parameter.

Next, where we want our sidebar widgets to be displayed, we use the dynamic_sidebar( $index ) template tag. This function calls each of the active widgets in order, generating the markup for the sidebar. The dynamic_sidebar() function also returns true on success and false on failure.

In Summary

You’ve now seen the whole process for creating menus and sidebars in our WordPress Starter Theme. First you register it, and then you tell WordPress where you want it to show up. From here you can create more menus and sidebars for your theme, if you want! In fact, sidebars in the header and footer can make a theme quite powerful and easily customisable. Frameworks such as Gantry showcase the control which multiple widget areas can give a user over layout, design and content.

So, that’s it for this part! Don’t forget to check the GitHub Repository for more detailed information on each function and tag, and also the WordPress Codex for more detailed descriptions of each function used here.

In the next part, we’ll be concluding our WordPress Starter Theme series by breaking each part of the index.php file into their own files: header.php, sidebar.php and footer.php, and giving our theme some basic styles. See you there!

Share.

About Author

Founder and Lead Developer at Affinity4.ie, a web development agency in Galway, Ireland. Develops mosty with WordPress, Laravel, PHP, MySQL, Git, Github, Sass and Compass.

Leave A Reply