Skip to content
All gists
Back to GitHub
Sign in
Sign up
Sign in
Sign up
{{ message }}
Instantly share code, notes, and snippets.
petergus
/
nav_menu_first_last
Created
Jul 4, 2012
Star
1
Fork
0
Star
Code
Revisions
1
Stars
1
Embed
What would you like to do?
Embed
Embed this gist in your website.
Share
Copy sharable link for this gist.
Clone via HTTPS
Clone with Git or checkout with SVN using the repository’s web address.
Learn more about clone URLs
Download ZIP
add first/last classes to wordpress wp_nav_menu
Raw
nav_menu_first_last
//an issue is that if the last li has children the last class will be applied to the last child.
// ===== option 1, not used ===== //
function add_first_and_last($output) {
$output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1);
$output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
return $output;
}
add_filter('wp_nav_menu', 'add_first_and_last');
// ====== option 2, used ====== //
// This does the same actually, taken from http://css.dzone.com/news/wordpress-wpnavmenu-separator
function nav_menu_first_last( $items ) {
$pos = strrpos($items, 'class="menu-item', -1);
$items=substr_replace($items, 'menu-item-last ', $pos+7, 0);
$pos = strpos($items, 'class="menu-item');
$items=substr_replace($items, 'menu-item-first ', $pos+7, 0);
return $items;
}
add_filter( 'wp_nav_menu_items', 'nav_menu_first_last' );
Sign up for free
to join this conversation on GitHub
. Already have an account?
Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.