(CSS)クラスを1つのwp_nav_menu()に追加する方法は?
-
16-10-2019 - |
質問
編集
このqは現在1.000をはるかに超えているので、元の質問を削除しました。つまり、多くの人にとって重要であることを意味します - a)カスタムウォーカーなしで動作するものを見せることは簡単です。 ノート: それはかなり見かけないものだったので、私は元のQにのみ削除しました。
タスク
(管理者UI)外観>メニューを介して追加された特定のNAVメニュー内のすべてのNAVメニュー項目にCSSクラスを追加します。
関数
function wpse4388_navmenu_classes( $items, $menu, $args )
{
// prevent crashing the appearance > menu admin UI
if ( is_admin() )
return;
# >>>> start editing
// Nav menu name you entered in the admin-UI > Appearance > Menus (Add menu).
$target['name'] = 'Topnav';
// A targeted menu item that needs a special class - add the item number here
$target['items'] = array( (int) 6 );
# <<<< stop editing
// filter for child themes: "filter_nav_menu_{nav menu name}"
// the nav menu name looses all empty spaces and is set to lower
// if you want to use the filter, hook your child theme function into 'after_setup_theme'
$target = apply_filters( 'filter_nav_menu_'.strtolower( str_replace( " ", "", $target['name'] ), $target );
// Abort if we're not with the named menu
if ( $menu->name !== $target['name'] )
return;
foreach ( $items as $item )
{
// Add the class for each menu item
$item->classes = 'classes for all items';
// Append this class if we are in one of the targeted items
if ( in_array( (int) $item->menu_order, $target['items'] ) )
$item->classes .= ' only for a single item';
}
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'wpse4388_navmenu_classes', 10, 3 );
役に立ちましたか?投票することを忘れないでください! :)
解決
Horttcoreに似たことを言うことから始めます。
指定されたメニューに単純に異なるコンテナ要素を提供できない理由はありますか?それは、それを一意にスタイリングするのに十分な特異性を提供する必要があります。
ただし、メニューの場所に基づいてメニューのargを条件付けるためにこのようなことをすることができます。
function my_wp_nav_menu_args( $args = '' ) {
if( $args['theme_location'] == 'your-specific-location' )
$args = array_merge( array(
'container_class' => 'example',
'menu_class' => 'example2'
), $args );
return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
上記のコードは、Codexページに与えられた例に基づいています wp_nav_menu
, 、そして簡単に拡張することができます。
http://codex.wordpress.org/function_reference/wp_nav_menu
それが役立つことを願っています。
他のヒント
たぶん私はあなたを間違えたのかもしれませんが、なぜあなたのテーマにクラスを追加してみませんか?メニューを呼び出すときにクラスを指定します。
<?php wp_nav_menu( array( 'theme_location' => 'Top Nav', 'menu_class' => 'span-3' ) ); ?>
非常によく似た問題がありました。特定をターゲットにする必要がありました wp_nav_menu()
Aリンクをクラスに置き換えます。これがOPに関連する私の解決策です。
function theme_add_menuclass( $classes, $args ) {
if ( $args->theme_location == 'your-menu-location' ) {
return preg_replace( '/<li /i', '<li class="your-class"', $classes );
}
return $classes;
}
add_filter( 'wp_nav_menu_items', 'theme_add_menuclass', 10, 2 );
これを使用して、NAVメニューの任意の部分を交換できます。お役に立てれば。
メニュー項目にCSSクラスを追加するには、 外観>メニュー>画面オプション (画面の右上)そしてそれを確認してください CSSクラス チェックされています。これにより、各メニュー項目にCSSクラスを追加できます。複数のクラス名の場合、各アイテムをスペースで分離します。
my-class-one my-class-two