Time for action – registering a navigation menu

Let's start by registering the menu. This involves creating a new file called functions.php.

  1. Create a new blank file in your theme directory and name it functions.php.
  2. At the beginning of the file, type the following:
    <?php
    function register_my_menus() {
      register_nav_menus(
        array( 'header-menu' => __( 'Header Menu' ) )
        );
      }
    add_action( 'init', 'register_my_menus' );
    ?>
  3. Save the file.

What just happened?

We created a new file called functions.php and added a function to it to register a menu. The functions.php file is a special file which is used to store extra functions which the theme needs in order to work. This will be PHP code that isn't included in WordPress itself and isn't in your theme files, but is used by them.

Let's have a look at each line of the function we added:

  • <?php starts running PHP, this line must be the very first line of your file with no spaces before it.
  • function register_my_menus() { defines a new function with the name register_my_menus.
  • register_nav_menus( uses a WordPress function called register_nav_menus to tell WordPress that this is what we're doing here.
  • array( 'header-menu' => __( 'Header Menu' ) ) is an array with a list of menus that you're setting up. We're just setting up one menu here, the name WordPress uses for it will be header-menu and the name shown in the menus admin screen will be Header Menu.
  • ); closes our array.
  • } closes our function.
  • add_action( 'init', 'register_my_menus' ); makes things happen. Any actions using init will be run after WordPress has finished loading but before any content is sent to the browser. Here, we're telling WordPress to run the register_my_menus function as part of the init action which it will always run.
  • ?> stops the PHP. This must be the final line of the functions.php file with no spacing or empty lines afterwards.

Well done! You just defined your first function. Now let's add the code to our header.php file to make the menu appear.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset