wp_nav_menu() function is used by themes for displaying WordPress menus in theme header, 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:
wp_nav_menu();
let’s say this code will give output
<ul> <li class="current_page_item"> <a href="http://webania.net/">Home</a> </li> <li class="page_item page-item-2"> <a href="http://webania.net/about/">About Webania</a> </li> <li class="page_item page-item-481"> <a href="http://webania.net/demo-jquery-charts-for-wp/">Demo: Jquery charts for WP</a> </li> <li class="page_item page-item-547 page_item_has_children"> <a href="http://webania.net/our-plugins/">Our plugins</a> <ul class="children"> <li class="page_item page-item-392"> <a href="http://webania.net/our-plugins/category-chart/">Category chart plugin</a> </li> </ul>
With output buffering we can customize this output with php string functions. For example
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:
<ul> <li style="color:red;margin:5px" class="current_page_item"> <a href="http://webania.net/">Home</a></li> <li style="color:red;margin:5px" class="custom_li page_item page-item-2"> <a href="http://webania.net/about/">About Webania</a></li> <li style="color:red;margin:5px" class="custom_li page_item page-item-481"> <a href="http://webania.net/demo-jquery-charts-for-wp/">Demo: Jquery charts for WP</a></li> <li style="color:red;margin:5px" class="custom_li page_item page-item-547 page_item_has_children"> <a href="http://webania.net/our-plugins/">Our plugins</a> <ul class="children"> <li style="color:red;margin:5px" class="custom_li page_item page-item-392"> <a href="http://webania.net/our-plugins/category-chart/">Category chart plugin</a> </li> </ul>