[WordPress]wp_nav_menuの最初と最後にclassを追加する

CSSでレイアウトしているとナビゲーションの最初とか最後にclassを追加したい時がある。

参考:add first/last classes to wordpress wp_nav_menu

//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' );

例1より例2がオススメらしい。。。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)