How to create custom wordpress menu

WordPress had been using the conceptual term ‘menu’ as a mysterious feature until version 3.0. Presenting the new customization admin options back then revealed a whole new world for developers and users to tune up their themes and easily modify the standard navigation – horizontal or vertical components. If you want to squeeze the juice out of your menus, check out that Ultimate Guide to WordPress Menus!

What makes WordPress 3.0 menus so fancy?
Since version 3.0, WordPress supports custom menu alterations. When you login to your admin panel and reach the Dashboard, navigate to the Appearance tab and there you will find the Menus section.

I do have menus with my standard install as well, don’t I?
Most themes (including the default WordPress 3.0 Twenty Ten theme and the Twenty Eleven theme to be released in WordPress 3.2) support navigation menus. The standard configuration includes all of the pages created via the admin panel in the navigation menus. This is often unnecessary and leads to discomfort. We are naturally unable to control the number or the type of elements to add in the standard menu. That’s why further configuration is required to improve the quality of the theme itself by giving a real usability to the navigation.

How to enable custom menus in my theme?
The standard post-install WordPress themes are preconfigured for you and include that customization functionality. However, if you want to design your own theme and run a custom menu, you will need to add support for it in the functions.php file.

if ( function_exists('register_nav_menu')) {
'top-menu' =>__('brand new menu'), ) );

This would bond your theme to the core functionality for custom menus. Registering the ‘top-menu’ area will help you to later connect this placeholder to a menu of your choice in the admin panel.

How to call an existing menu in my theme?
By calling the wp_nav_menu function and using the theme alias:

wp_nav_menu(array('theme_location' => 'top-menu'));

This piece of code could be added anywhere in your theme templates. This is normally the header.php file to be included everywhere in your theme or in a specific file such as single.php or category.php if you want it to be visible only in a single post view or on category listing. It’s up to you where would be the appropriate position for your menu!

The code snippet inserts the menu with the standard options that you could alter on demand. Here it is the complete function call with the default parameters:

'theme_location' => 'top-menu',
'menu' =>,
'container' => 'div',
'container_class' => 'menu-{menu slug}-container',
'container_id' =>,
'menu-class' => 'menu',
'menu_id' =>,
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' =>,
'after' =>,
'link_before' =>,
'link_after' =>,
'items_wrap' =>, 
‘depth’ => 0, ‘walker’ => ) );

Here is a reference guide for the available parameters:

Theme_location The theme location (menu area) defined in the register_nav_menu()function
Menu Menu locator – looking in menu list by id, slug or name (in that order)
Container Preferred wrapper for the

    tag – could be ‘div’, ‘nav’ or none (denoted by false).
Container_class, Container ID CSS class or id to be applied to the container (if any)
Menu_class, Menu_d Same for the menu element
Echo Print the evaluated menu or return it as a variable (‘0’ for return)
Fallback_cb A function to be executed if the menu does not exist
Before, After Text to be applied before or after the anchor link tag
Link_before, Link_after Text inserted between the link text in the anchor
Items_wrap Formatting string for the items list. By default using

    which is actually optional.
Depth Sets the maximum depth of the hierarchy (useful to reduce visibility problems with dropdown menus)
Walker Normally won’t be changed, defaults to Walker_Nav_Menu iterator

If your slicer has provided you with a standard HTML template or you want to integrate one as a WordPress theme, you won’t need to modify the slice –you can control the output of the menu function by the platform instead!

What could I do with my menus?
The menu manager is pretty powerful. First of all, you need to create your first menu. In the “Menus” section, enter the name of your new menu and click the “Create Menu” button.

By default all brand news are empty. You could check the “Automatically add new top-level pages” checkbox if you want to simulate the default functionality that includes all of the pages (from the Pages admin list) to your menu. In addition to that now you could filter the items by explicitly point all of the items for your menu.

You could chose only specific pages from the panel on the left to your menu. They could be ordered as you prefer and even be nested which would result in a dropdown menu (if your theme supports one)

Ordering is drag&drop based so you don’t need to cope with indices anymore – rearrangement is done via dragging an item and positioning it as a root element for the menu or a child element to an existing item. Dropdowns could be few levels deep if you need more complex hierarchy. You could also attach links or categories to the menu – in case you need to link an internal page or external website – it is now doable within the admin panel. No more code changes required.

Note: Changes to the menu should be saved explicitly!

Am I able to add more than 1 menu to the theme?

Sure, why not? You could recall any menu by its name anywhere in your theme. For instance, you could define one horizontal menu below the header and a vertical one with other items in the footer. Also the “Menus” section counts the number of menus supported by your theme and you can switch menu configurations “on the fly”.

You could define different areas in your WordPress theme where each area operates with a different menu. Register a new navigation menu and attach it to your theme. Modifying the standard Twenty Fifteen theme we will add the Additional menu to the Primary one in the functions.php file:

register_nav_menus( array(
'primary' => __('Primary Navigation', 'twentyten'),
'additional' => __('Additional Navigation', 'twentyten'),
) );

We are using the register_nav_menus here to perform similar actions with many objects. Updating these rows in the functions.php file results to 2 dropdowns for you to select menus in your WordPress Menus section. Let’s create one more menu and name it second menu. Now we have 2 tabs with both menus in the right column.

We could fill the second menu with data. Let’s start with that scenario of nested pages, links and categories and model it as a menu:

  • Page [Level 1]
    • SubPage [Level 2]
      • Deeper SubPage [Level 3]
  • Custom Top Link [Level 1]
  • Top Category [Level 1]

Add one WordPress page as the first element. The next page will be a subpage of the first one (it could be a child page, but it could also be any single page from your database). We could even add a third page to be a third-level element in your dropdown hierarchy so that the third page is under the second which is visible after hovering on the first one.

In addition to that hierarchy we could add an external link to an example website and a category item as well. Note that we have changed the menu titles of the pages regardless the fact that they exist with different titles in the Pages section.

Can I link to a custom post type as well?

A custom post type item could be added to a menu in the “Menus” section if its visibility is activated in your theme. This could be done by adding the following parameter to theregister_post_type function in functions.php or other file where your custom type has been defined:

'show_in_nav_menus' => true

The post type would then be linkable.


We end this tutorial empowered with the knowledge of adding custom menus to our existing WordPress theme in an elegant and clean way. We have learned the following concepts:

  • Adding a Custom Menu support to the theme
  • Applying a Custom Menu in different areas in the frontend (the placeholders in the visual template)
  • Filling menus with pages, categories, custom URLs
  • Creating several menus and managing them
  • Using the “Custom Menu” widget
  • Adapting custom types to be visible in the Menus section

Already excited? Run your favorite text editor and tune up your WordPress theme right away!

Continue Reading

How to develop a wordpress plugin

When you begin building a WordPress plugin, there are a lot of things you need to keep in mind: the functionality of the plugin, the target audience, how it is going to be distributed, how you are going to provide support for it, etc. There is another aspect of the development process that is often overlooked or pushed to the sidelines, and that is the set of general strategies you are going to use during your development.

When I say “general strategies”, I’m referring the things like the basic file / folder organization, the naming scheme for your files, the organization of functions within files, and the way that resources are loaded. It is best if you make an effort to keep these aspects constant throughout your development. When you use the same basic strategies for each of your projects, and throughout each individual project, you will find that it dramatically improves your workflow and the overall quality of your work.

Imagine you are writing a plugin that has upwards of 10,000 lines of code; which do you think is easier to enhance and debug, a plugin that has the 10,000 lines separated into meaningfully named files and folders, or a plugin that has all 10,000 lines in a single file? If you have answered with a single file, then I’d highly advise you to think about it a little longer, or challenge yourself to go write a very large plugin, and do it all in one file. You will quickly find that it’s highly disadvantageous.

I would like to discuss and share several aspects of my personal development strategy. Some of these are simply things that should be done because WordPress Coding Standards dictates that we should (with good reason), and some of them are strategies that I have simply found to be extremely helpful in development.

Use a Unique Prefix for Everything

This is one of the first rules of development, and it should never, ever be broken. When you write your plugin, everything absolutely must receive a unique prefix specific to your plugin. This includes function names, class names, global variables, option names, database tables and more.

The primary reason for always, without exception, using prefixes is that it prevents conflicts. If two plugins (or themes) use the same name for a function, and both are active at the same time, they will cause a fatal error, since all function names must be unique.

For example, you might have a function in your plugin like this:

load_plugin_scripts() {
    // script loading happens here

But this is a terrible name, because if any theme or other plugins also has a function named load_plugin_scripts, a fatal error will be thrown. Let’s imagine for a moment that your plugin is named “Load Posts with Ajax”. I usually create my prefixes by taking the first letter of each word in the plugin’s title, so our prefix will be “lpa_”, or “lpwa_”, which means our function should be this instead:

// plugin folder path
// plugin folder url
if(!defined('LPA_PLUGIN_URL')) {
	define('LPA_PLUGIN_URL', plugin_dir_url( __FILE__ ));

Define Constants for File Paths and URLs

This mostly applies to large plugins, but can be useful with smaller ones as well. The absolute path to your plugin’s folder can be used for including extra plugin files, loading templates, and a few other things. I usually define a constant with the path to the plugin’s directory like this:

// plugin folder path
// plugin folder url
if(!defined('LPA_PLUGIN_URL')) {
	define('LPA_PLUGIN_URL', plugin_dir_url( __FILE__ ));

Remember that “LPA_” is the prefix we created for our plugin above.

It is also a good idea to define a constant for the plugin directory’s URL. This will be used for loading assets, like images, CSS files and Javascript files.

// plugin folder path
// plugin folder url
if(!defined('LPA_PLUGIN_URL')) {
	define('LPA_PLUGIN_URL', plugin_dir_url( __FILE__ ));

While these constants are not entirely necessary, they do make things easier in the long run. Instead of figuring out the file path or URL every time you need it, you simply call the constant. In large plugins this can save a lot of time.

Organize Your Plugin Into Multiple Files

When you are working with a plugin that has a large amount of code, then separating it into multiple files is one of the best things you can do. You should separate your code into “blocks” that are organized based on what they do. For example, all of your short code definitions should go into a file called “shortcodes.php” (or similar). All of your code that relates to loading CSS or jQuery should go into a file named perhaps “scripts.php”.

By separating your code into “blocks” that are each placed into meaningfully named files, you make your job as the developer much easier on yourself. It is suddenly dramatically easier to locate the code you’re looking for, especially when debugging errors. When you want to enhance the functionality of your plugin, perhaps by adding another short code, you immediately know where the new code should go: shortcodes.php.

With smaller plugins, this is not always the case, however. A small plugin with just 100 lines of code could easily be all placed into a single file and still be very manageable, but even in this case, I would still advise you to separate it into multiple files. The main reason for doing this is that it opens the door to further development and expansion. It is a lot easier to organize your plugin early on when there is only a small amount of code than it is to reorganize later once you have thousands of lines.

Once your plugin is separated into multiple files, you will pull the files into the main plugin file like this:

include_once( LPA_PLUGIN_DIR . 'includes/shortcodes.php' );

Note that I advise you place all of your extra files into sub directories as well. I usually place my files into a folder called “includes” (because these are included into the main file), and this directory will often have sub directories within it as well.

My plugin folder structure usually looks something like this:

  • my_plugin_folder_name
    • includes
      • admin-pages
      • templates
    • js
    • css
    • images

Format Your Code

There is very little more frustrating to a developer than opening some one else’s code and finding that it is a formatting nightmare. Messy code is usually bad code. A very simple way that you can dramatically help yourself in your development, and help anyone that works with your code, is by taking the time to format your code nicely and consistently.

Code should have even indention (I prefer tabs, not spaces) and consistent line breaks. When a chunk of code is nested inside of conditional or switch (or other) statements, it should be indented. Take this bad code for example:

if( $conditional ) {

While there are only two lines inside of the conditional, this is still much harder to read and follow than a block that is properly indented:

if( $conditional ) {

Just imagine how hard it is to read a plugin that has 100s or 1000s of lines of code that isn’t properly indented. It becomes a debugging nightmare.

Do yourself and everyone else a favor: indent and format.

Do Not Reinvent the Wheel

There are a lot of APIs and methods built into WordPress that are designed to make your job as a developer easier, so utilize them and save yourself the trouble of building your own solution.

For plugin options, use the Settings API. This API can be a bit confusing to work with at first, but once you figure it out, it is really quite simple, and extremely powerful. Tom McFarlin wrote a phenomenal tutorial series on using the Settings API, if you are unsure about it then definitely check his series out.

For showing data in your plugin in a table format (like Posts and Pages), there is a class called WP_List_Table. This class will do all of the heavy lifting for you, including pagination, filtering, bulk actions, etc, all you have to (to start at least) is provide an array of data to populate the table with.

When creating custom admin screens, make sure of core WordPress CSS. There is absolutely no reason to write dozens (or hundreds) of lines of CSS to style your custom admin pages when, instead, you could use the core styles included with WordPress. There is a pretty decent guide to admin styles at One Extra Pixel.

There are many other general strategies that you can use during development, but these alone will help you tremendously if you choose to follow them.

Continue Reading