Displaying a menu using the wp_nav_menu function. Adding a menu to your template using CMS WordPress
We invite you to familiarize yourself with new technology on creating a responsive (adaptive) menu without using Javascript. She uses clean and semantic markup HTML5. The menu can be aligned left, center, or right. This menu switches on hover, which is more convenient for users. It also has an indicator that shows the “running/threading” menu item. It works on all mobile and desktop browsers including Internet Explorer!
Target
The purpose of this lesson is to show you how to regular menu make a drop-down menu on a small display.
This trick will be more useful for navigation with a large number links as in the screenshot below. You can condense all the buttons into an elegant dropdown menu.
Nav HTML markup
Here is the markup for navigation. The tag is required to create a drop-down menu with CSS property absolute position. We'll explain this in a lesson later. The .current class points to the active/current menu links.
- Portfolio
- Illustration
- Web Design
- Print Media
- Graphic Design
The CSS for navigation (desktop view) is pretty basic, so we're not going to go into too much detail here. Note that we specified display:inline-block instead of float:left in the element's NAV
- element.
- specifying display:none, but leaving .current
- displayed as a block. Then on the NAV hover, we set everything
- to display:block (this will give the result of the dropdown list). We've added a graphical icon to the check.current element to indicate that the element is active. To align the menu center and right, use the left and right positioning property
- list.
- items */ margin: 0; ) .nav .current ( display: block; /* show only current
- item */ ) .nav a ( display: block; padding: 5px 5px 5px 32px; text-align: left; ) .nav .current a ( background: none; color: #666; ) /* on nav hover */ . nav ul:hover ( background-image: none; ) .nav ul:hover li ( display: block; margin: 0 0 5px; ) .nav ul:hover .current ( background: url(images/icon-check.png) no-repeat 10px 7px; ) /* right nav */ .nav.right ul ( left: auto; right: 0; ) /* center nav */ .nav.center ul ( left: 50%; margin-left: - 90px; ) )
High conversions!
Navigation is present on any good website, even if it is a one-page one. Depending on the situation, navigation links can lead to various sections of the site or send to a bookmark (anchor) located on current page. Competently designing navigation in which the user does not get confused requires certain knowledge and experience. To design navigation bar you also need to approach it wisely, and in this lesson we will tell you how to create a convenient navigation menu.
Creating NavigationWhat is navigation? This is a collection of links, often ordered and grouped by meaning. A navigation menu is often created using an HTML list tag
- , where at each point
- contains one link . In HTML5, a separate tag was introduced for navigation, where you can simply place link tags. Once you've created the HTML framework, you can move on to styling it with CSS, where you can define how your menu will be vertical, horizontal, drop-down, etc.
Let's say we have a simple navigation with five links, created in HTML based on a bulleted list:
Initially, without styles, our navigation looks like a regular list:
To make this element more like a navigation bar, there are a few required steps you need to take. Firstly, markers are not needed near menu items, and secondly, standard values The margin and padding set by the browser for the list can get in the way, so we set them to zero. The result is the following:
Menu ( list-style-type: none; margin: 0; padding: 0; )
Essentially, the style reset file performs identical actions in relation to lists Reset.css, therefore, if you use it on your site, then the code above does not need to be written.
After resetting the standard list styles, you can proceed directly to creating styles for navigation. We'll show you how to make vertical and horizontal panels.
Vertical menuCreating a vertical navigation bar is considered easier than creating horizontal menu. Mainly because there is no need to set the links to be horizontal. It's simple vertical list site pages. Still, some important styles will have to be applied.
Block linksFirst of all you need to make all the tags block elements:
Menu a ( display: block; )
There are several reasons for this:
Menu widthThe next thing we need to do is set the width of the menu. If you haven't pre-defined the width of the navbar, and it's not in a container that bounds it, then the menu will stretch across the entire width of the window (as in our example above) - because that's how a block element behaves by default. You can set the required width for the .menu element, for example:
Menu (width: 300px; )
Instead, you can set the width for the items
- or for links - visually the effect may be the same, but keep in mind that in this case the width of the .menu element will still remain 100%.
Separating itemsTo visually separate menu items, you can give each of them a lower or upper border. Depending on which one you use, you will have a missing border at the top or bottom of the menu. This can be fixed by adding another border to the .menu block itself:
Menu a ( border-top: 1px solid blue; ) .menu ( border-bottom: 1px solid blue; )
Point Height and Vertical AlignmentRight now the menu links look too low and too close together. If the text of each link does not occupy more than one line, then you can increase their height and keep the text vertically centered using the height and line-height properties:
Menu a ( height: 30px; line-height: 30px; ) GIF
As you can see in the animation, the height property affects the height of the link, and the line-height line spacing changes the height of the text line itself. Be sure to set the same values for these two properties if you want the link text to be vertically centered.
Horizontal menuThe main task when creating horizontal navigation is to arrange menu items in one row. This can be done in several ways.
Method oneThe first option is to set the display property of the list items with the value inline or inline-block:
Menu ( display: inline; )
After this, you can start creating links. For example, you can make this style:
Menu a ( text-decoration: none; font-family: sans-serif; color: #5757a0; display: inline-block; padding: 10px 20px; background-color: lavender; border-bottom: 5px solid #5757a0; )
We added a background color and a bottom border to each link, and increased its size using padding. Note that there are small gaps between menu items, although we did not add them via styles. They occur because the browser interprets the carriage return character between the closing and opening tags this way.
- . These gaps can be removed by writing the list HTML code on one line:
However, this is inconvenient, because these changes will have to be made to the HTML manually, and the code will be difficult to read. Therefore, you can try to get rid of gaps using a negative margin-right value:
Menu li ( margin-right: -5px; )
This code does not remove the gaps, but covers them by shifting the elements five pixels to the left. This method cannot be said to be very reliable because the size of the gap may vary depending on other styles.
If the spaces between points are not planned in your design, it is better to use the second method of horizontal alignment of elements.
Method twoYou may have already guessed that the second option for creating a horizontal menu is to use the float property. To do this, add a style for the tags
- :
Menu li ( float: left; )
As you can see, there are no longer any gaps between points. All other styles work as before. But if you add another HTML element after the navigation (let's say ), it will be affected by the wrapping and will be aligned with the menu items. You can cancel this action by adding the clear: left property to the header. But when developing a site with a large number different pages It can become difficult to keep track of where you forgot to indicate this property. It's much easier to undo the wrapping on the navigation side. This entry will help with this:
Menu ( overflow: hidden; )
This will also help return the parent of the floated elements to their normal height. We already talked about this problem in previous lessons, but then we solved it through a special hack using the pseudo-element:after . The example above is another way to solve the issue with the missing container height.
Note: If you set a background for a .menu element, you won't see it until you apply overflow: hidden to it. Logical, because how can you see the background of an element whose height is zero?
In the next lesson we will talk in more detail about the capabilities of attribute selectors, with which you can set
In the blog article before last, I wrote about interesting innovations latest version WordPress is a special mechanism for creating and managing . Now it has become much more convenient and easier ordinary users create menus of varying complexity, which can consist not only of pages or blog categories, but also have links to any URL. To display the menu in the template, a special function wp_nav_menu is used - I’ll tell you about it today.
If in WordPress admin there is no menu section, it can be activated by adding special code to the functions.php file
Here first is the name of the menu we created. This is the use of a function in the general case without widgets; you will need to work with them a little differently there. However, the wp_nav_menu function can be output without arguments, resulting in “browsing” different situation— first, a match by menu name if at least one menu item is specified for it, otherwise a non-empty menu will simply be displayed, etc. But again, I advise you to simply use the code above and not figure out what the function without arguments should output. Its syntax is as follows:
The following parameters are used here:
$menu - the selected identifier for the menu - ID, slug or menu name.
$container - The default UL menu is "wrapped" in a DIV container using this setting.
$container_class - indicates the class of the container; by default its value is menu-(menu slug)-container, that is, in our case, for example, the class will be menu-first-container.
$container_id - you can add an ID to the container, not specified by default.
$menu_class is the class for the UL menu element, its value is menu.
$menu_id — ID for the ul element, defaults to menu-(slug)
$echo - if you do not want to display the menu, but return the value of the function, use 0 for this setting.
$fallback_cb - if the menu does not exist, the wp_page_menu function is called.
$before - sets the text that is displayed before link A.
$link_before — displays the phrase before the link text, not specified.
$link_after — displayed after the link text, also empty.
$depth - sets the number of hierarchy levels to display the menu; the default value of 0 displays the entire menu.
$walker - some kind of incomprehensible custom “walker object”, probably more needed by advanced developers.
$theme_location - The location of the theme where the menu will be used must be activated via register_nav_menu() in order for the user to be able to select it. Also some kind of not entirely clear setting, apparently, when working with widgets.
Examples of using the wp_nav_menu functionThe simplest code given in the code is:
Removing the DIV container from the menu
In principle, there is nothing complicated in creating and managing wordpress menu 3.0 no. The developers have significantly simplified the work procedure and expanded the capabilities of this element navigation. The solution is often used in a variety of template tasks, for example, when creating for mobile and desktop versions. A little later I will add a couple more snippets on the topic.
P.S. Guard. Interesting and useful for webmasters SEO blog, where you will find answers to your SEO questions.
The Aweb company has long established itself very well in the field of website promotion, optimization and search engine promotion on the Internet.Register and display a custom menu created in the panel: “ Appearance> Menu" (Appearance > Menus).
Registering the menu
Add_action("after_setup_theme", function())( register_nav_menus(array("main_menu" => __("Primary menu", "crea"), "foot_menu" => __("Footer menu", "crea"),)) ; ));
The second option for registering the menu (I don’t know how correct it is, so it’s better to use the first option)
If (function_exists("register_nav_menu")) ( register_nav_menus(array("main_menu" => __("Primary menu", "crea"), "foot_menu" => __("Footer menu", "crea"),)) ; )
Displaying the menu
Second menu option
Usage
wp_nav_menu(array("theme_location" => "" // (string) The location of the menu in the template. (indicates the key with which the menu was registered in the function "menu" => "", // (string) The name of the displayed menu (indicated in the admin panel when creating a menu, priority is given to specified location theme_location - if specified, the theme_location parameter is ignored) "container" => "div", // (string) Menu container. Wrapper ul. The container tag is indicated (by default in the div tag) "container_class" => "", // (string) class of the container (div tag) "container_id" => "", // (string) id of the container (div tag) "menu_class " => "menu", // (string) class of the menu itself (ul tag) "menu_id" => "", // (string) id of the menu itself (ul tag) "echo" => true, // (boolean ) Display or return for processing "fallback_cb" => "wp_page_menu", // (string) The (fallback) function to use if the menu does not exist (could not be retrieved) "before" => "", // (string) Text before each link "after" => "", // (string) Text after each link "link_before" => "", // (string) Text before the anchor (text) of the link "link_after" => "", // (string) Text after the anchor (text) of the link "items_wrap" => "", "depth" => 0, // (integer) Nesting depth (0 - unlimited, 2 - two-level menu) "walker" => "" // (object) Class that collects menus. Default: new Walker_Nav_Menu));
$args Parameter Arguments
theme_location(string)
ID of the menu location in the template. Identifier specified when registering a menu using the register_nav_menu() function.
Default: ""menu(string)
The menu that needs to be displayed. Match: id, slug or menu name.
Default: ""container(string)
How to wrap the ul tag. Acceptable: div or nav.
If you don’t need to wrap it with anything, then write false: container => false.
Default: divcontainer_class(string)
The value of the class attribute of the menu container.
Default: menu-(menu slug)-containercontainer_id(string)
The value of the id attribute of the menu container.
Default: ""menu_class(string)
The value of the class attribute of the ul tag.
Default: menumenu_id(string)
The value of the id attribute of the ul tag.
Default: menu slugecho(boolean)
Print to screen (true) or return for processing (false).
Default: truefallback_cb(string)
A function to process the output if no menu is found.
Passes all $args to the function specified here.
Set the empty string to " or '__return_empty_string' to display nothing if there is no menu.
Default: wp_page_menubefore(string)
Text before tag on the menu.
Default: ""after(string)
Text after each tag in the menu.
Default: ""link_before(string)
The text before the anchor of each link in the menu.
Default: ""link_after(string)
Text after the anchor of each link in the menu.
Default: ""items_wrap(string)
Do I need to wrap elements in a ul tag? If necessary, a wrapper template is specified.
Default: ""depth(number)
How many levels of nested links to show. 0 - all levels.walker(object)
The class that will be used to build the menu. You need to specify an object, not a string, for example new My_Menu_Walker(). Default: Walker_Nav_Menu(). See below for how to use...
Default: Walker_Nav_Menuitem_spacing(string)
Whether or not to leave line breaks in the HTML menu code. Could be: preserve or discard
Default: "preserve"Example
Show menu only if it exists
By default, if there is no menu, the site pages will be displayed instead. But if you need to display the menu only when it is created in the admin panel, specify the fallback_cb parameter as "__return_empty_string" :
Wp_nav_menu(array("theme_location" => "primary-menu", "fallback_cb" => "__return_empty_string"));
Creating a menu in WordPress, as well as sorting pages and categories, often becomes a rather difficult problem for novice webmasters. Because of this, I decided to write a short tutorial in which we will take a detailed look at how to create custom menus in WordPress. With their help, you can create custom menus yourself, add or remove menu items, change their name, location and nesting.
In one of the previous articles we already looked at the method. Fortunately, WordPress now has a built-in feature that allows you to create custom menus without resorting to plugins. This feature is available in all versions of WordPress starting from version 3.0.
I would like to immediately draw your attention to the fact that support for custom menus is not enabled in all templates. In this regard, the article will consist of two parts. In the first part of the article, we will look at how to create menu items in WordPress through the admin panel if custom menus are already included in the template.
In the second part of the article, we will learn how to independently enable support for custom menus in WordPress and customize menu display via wp_nav_menu. This knowledge will be useful to you in case your template does not provide for the use of custom menus, or you write it yourself, or want to add the ability to create custom menus.
Creating menus and custom menu items through the WordPress admin panelTo create a menu, go to the Administrative Panel – Appearance – Menus and see if support for custom menus is enabled in your template. If not, then we can skip this step for now and go straight to the second part of the article. If the menu is already supported, then you will see a page with approximately the following content.
To create a new menu, enter its name in the “Enter menu title” field and click “Create menu”.
Personally, I prefer to write all names in Latin letters to avoid any problems in the future. Cyrillic names are also supported, but I would not recommend you to use them. This is my personal opinion.
After creating the menu, we need to select it in the “Topic Areas” block, which is located in the left column, and then save the result by clicking on the “Save” button.
In this case, the theme supports only one custom menu, so you don’t have to choose much. You just need to select the menu we created from the drop-down list and save the result. If the theme supports two or more menus, then you need to select the menu based on its location in the template.
After saving the results, to add new items to the menu, just mark the desired categories or pages and click the “Add to Menu” button.
After this, they can be moved relative to each other as desired and the nesting can be changed.
So, we looked at how to create a custom menu through the WordPress admin panel, how to add new items to it and configure them. Now let's move on to the second part of the article and learn how to enable support for custom menus in WordPress and display them in the template using the wp_nav_menu function.
Enable custom menu support in WordPressFirst of all, we need to register the use of custom menus and the menus themselves. To do this, open the function.php file of your theme for editing and add the following code.
Register_nav_menus(array("top" => "Top menu"));
Where “top” is the menu identifier, and “Top menu” is the name of the location.
If you need to add several menus, then list them separated by commas.
Register_nav_menus(array("top" => "Top menu", "left" => "Left menu"));
After adding this code, support for custom menus will be enabled automatically. You can verify this by going to the Administrative Panel – Appearance – Menu. But the menu registration itself is not enough. The menu still needs to be displayed in the template. To do this, we will use the special wp_nav_menu function.
Display a custom menu. wp_nav_menu functionAs mentioned above, we will display custom menus using the wp_nav_menu function, which can accept the following parameters.
$args = array("menu" => "", // Menu name (string). "container" => "div", // Menu container (string). The ul list is placed in it. "container_class" => " ", // Container class (string). "container_id" => "", // Container Id (string). "menu_class" => "menu", // ul tag class (string). "menu_id" => " ", // Id of the ul tag (string). "echo" => true, // Display or return for processing (boolean). "fallback_cb" => "wp_page_menu", // Backup function in case an arbitrary menu does not exist (string). "before" => "", // Text before each link (string). "after" => "", // Text after each link (string). "link_before" => "", // Text before the link anchor (string). "link_after" => "", // Text after the link anchor (string). "depth" => 0, // Nesting depth (integer). 0 - unlimited, 2 - two-level custom menu. "walker" => , // Class that collects menus. Default: new Walker_Nav_Menu. (object). "theme_location" => ""); // The location of the menu in the template. Specify the menu ID. (string).
In this case, parameters can be passed both through an array and through a string. In any case, the menu will work. For clarity, let's consider both options.
Passing parameters through an array
Passing parameters via string
Wp_nav_menu("menu_id=topmenu&theme_location=top&container=");
Personally, I prefer the second option, as it is more compact, in my opinion. In any case, the result of the function will be the following code.
This is where I end this article. We have reviewed the main points and in 99% of cases this information will be enough for you to create your own custom menus in WordPress. If you have any questions, you can always ask them in the comments.
That's all. Good luck and success in creating websites on WordPress.
- or for links - visually the effect may be the same, but keep in mind that in this case the width of the .menu element will still remain 100%.
- contains one link . In HTML5, a separate tag was introduced for navigation, where you can simply place link tags. Once you've created the HTML framework, you can move on to styling it with CSS, where you can define how your menu will be vertical, horizontal, drop-down, etc.
@media screen and (max-width: 600px) ( .nav ( position: relative; min-height: 40px; ) .nav ul ( width: 180px; padding: 5px 0; position: absolute; top: 0; left: 0 ; border: solid 1px #aaa; background: #fff url(images/icon-menu.png) no-repeat 10px 11px; border-radius: 5px; box-shadow: 0 1px 2px rgba(0,0,0,. 3); .navli ( display: none; /* hide all
/* nav */ .nav ( position: relative; margin: 20px 0; ) .nav ul ( margin: 0; padding: 0; ) .nav li ( margin: 0 5px 10px 0; padding: 0; list-style: none; display: inline-block; ) .nav a ( padding: 3px 12px; text-decoration: none; color: #999; line-height: 100%; ) .nav a:hover ( color: #000; ) . nav .current a ( background: #999; color: #fff; border-radius: 5px; )
Center and right alignment
As mentioned above, you can change the button alignment using “text-align”.
/* right nav */ .nav.right ul ( text-align: right; ) /* center nav */ .nav.center ul ( text-align: center; )
Internet support Explorer
HTML5 tag and media queries are not supported by Internet Explorer 8 and older versions. Include CSS3-mediaqueries.js (or respond.js) and html5shim.js to provide fallback support. If you don't want to add html5shim.js, then replace the tag with a tag.
This is where the fun begins - making menus responsive with media queries! At 600px we set the nav element to a relative position so that we could place
- menu list at the top with absolute position. We have hidden all elements