Simple way to add styles and classes to WordPress nav menu

wp_nav_menu() function is used by themes for displaying WordPress menus in them eheader, footer, sidebar.
Sometimes you need to customize nav menu with your own html tags, styles and classes. The normal way to do it is WordPress Walker, which we talked about in another post. Although this is the only perfect way to solve this task, this way is a little long and difficult. Sometimes we may need quicker solution for little customization in nav menu. In such cases we can use php output buffering. Here is sample:
Have you ever thought about highlighting particular link in WordPress menu ?. For example,You can highlight “Hire Us” link in navigation to get readers attention,which helps to get high conversion.
Interestingly,WordPress offers a feature called custom CSS class,Through which we can easily style the individual links of navigation menu.
In this tutorial I am going to throw some lights on using this feature with couple of examples.
let’s say this code will give output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| < ul > < li class = "current_page_item" > </ li > < li class = "page_item page-item-2" > </ li > < li class = "page_item page-item-481" > </ li > < li class = "page_item page-item-547 page_item_has_children" > < ul class = "children" > < li class = "page_item page-item-392" > </ li > </ ul > |
With output buffering we can customize this output with php string functions. For example
1
2
3
4
5
6
7
8
9
10
11
| ob_start(); wp_nav_menu(); $menu_output =ob_get_clean(); //now let's add custom_li class to the menu elements. $menu_output = str_replace ( '"page_item ' , '"custom_li page_item ' , $menu_output ); //or we may want to add some styles to elements. $menu_output = str_replace ( 'li class=' , 'li style="color:red;margin:5px" class=' , $menu_output ); //print final result echo $menu_output ; |
That’s all. The final output will be like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| < ul > < li style = "color:red;margin:5px" class = "current_page_item" > < li style = "color:red;margin:5px" class = "custom_li page_item page-item-2" > < li style = "color:red;margin:5px" class = "custom_li page_item page-item-481" > < li style = "color:red;margin:5px" class = "custom_li page_item page-item-547 page_item_has_children" > < ul class = "children" > < li style = "color:red;margin:5px" class = "custom_li page_item page-item-392" > </ li > </ ul > |
Simple way to add styles and classes to WordPress nav menu
Reviewed by Unknown
on
1:47 AM
Rating:

No comments: