Monday, July 15, 2013

Changing the navigation html

When I started making/modifying Wordpress themes I was unfamiliar with PHP. Then it came time to change a navigation menu. I searched and searched for the html that was to be used to construct the menu. Much can be done with CSS and I know much more than I did then. However, I needed more html elements to style.

When Wordpress builds a menu that has been created in the "appearance->menus" section of wp-admin  page, it uses what they call a "Walker". Essentially, it loads the database entry where the menu is stored which is just a long string of letters and symbols and cuts it into pieces and wraps those pieces in html. To change the html that it writes you can do it the hard way (which is what I did) and write a custom walker, or you can simply add some options when inserting the wp_nav_menu() function.

We are doing this already when we insert a specific menu this example would insert the menu named 'my main nav menu'

<?php
wp_nav_menu( array('menu'=> 'my main nav menu') );
?>

The same thing can be done by putting that array into a variable like so...

<?php
$parameters = array('menu'=> 'my main nav menu')
wp_nav_menu( $parameters );
?>

This is what is going on in the Wordpress Codex mentioned earlier

<?php
$defaults = array(
 'theme_location'  => '',
 'menu'            => '',
 'container'       => 'div',
 'container_class' => '',
 'container_id'    => '',
 'menu_class'      => 'menu',
 'menu_id'         => '',
 'echo'            => true,
 'fallback_cb'     => 'wp_page_menu',
 'before'          => '',
 'after'           => '',
 'link_before'     => '',
 'link_after'      => '',
 'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
 'depth'           => 0,
 'walker'          => ''
);
wp_nav_menu( $defaults );
?>

To wrap each anchor tag in something like say "<div class='something'></div>"
change the above parameters (The Wordpress Codex uses the word defaults) change it to look like this

<?php
$parameters = array(
 'menu'            => 'my main nav menu',
 'link_before'     => '<div class='something'>',
 'link_after'      => '</div>'
)
wp_nav_menu( $parameters );
?>

Looks easy right? That's because it is.
The parts where the defaults use things like '%1%s' and '%2$s' and '%3$s' are inserting variables.
Try it out and see what happens when you put stuff in for the 'before' and 'after' parameters.

No comments:

Post a Comment