Как оформить первый и последний пункт меню в WordPress - PullRequest
1 голос
/ 15 октября 2010

Как добавить класс к первому и последнему пункту в меню?

Ответы [ 7 ]

1 голос
/ 08 ноября 2012

Без использования jQuery: начиная с CSS2 вы можете использовать селекторы: first-child и: last-child.Например, настраивая поля для этого меню, в зависимости от его порядка:

<ul class="nav">
    <li> <a href='/x1'>One</a> </li>
    <li> <a href='/x2'>Two</a> </li>
    <li> <a href='/x3'>Three</a> </li>
    <li> <a href='/x4'>Four</a> </li>
</ul>

выберите пункты меню следующим образом:

.nav > li > a { //selects ALL menu items
    padding: 20px;
}
.nav > li:first-child > a { 
    // selects the FIRST menu item, aka the first child 'li' of its parent '.nav'
    padding-left: 0px;
}
.nav > li:last-child > a { 
    // selects the LAST menu item, in this case 'Fourth'
    padding-right: 0px;
}
1 голос
/ 19 октября 2010

Решение jQuery самое простое:

Добавьте это в ваш файл скрипта:

$("ul li:first").addClass("first");
$("ul li:last").addClass("last");
0 голосов
/ 15 июня 2013

Я использую следующий фильтр, который добавляет класс первым и последним

в меню
function wpb_first_and_last_menu_class($items) {
    $items[1]->classes[] = 'first-menu-item'; // add first class

    $cnt = count($items);
    while($items[$cnt--]->post_parent != 0); // find last li item
    $items[$cnt+1]->classes[] = 'last-menu-item'; // last item class
    return $items;
}
add_filter('wp_nav_menu_objects', 'wpb_first_and_last_menu_class'); //filter to iterate each menu
0 голосов
/ 13 мая 2013

Я нашел это решение, которое у меня сработало:

Добавление первых / последних классов CSS в меню

add_filter( 'wp_nav_menu_objects', 'tgm_filter_menu_class', 10, 2 );
/**
 * Filters the first and last nav menu objects in your menus
 * to add custom classes.
 *
 * This also supports nested menus.
 *
 * @since 1.0.0
 *
 * @param array $objects An array of nav menu objects
 * @param object $args Nav menu object args
 * @return object $objects Amended array of nav menu objects with new class
 */
function tgm_filter_menu_class( $objects, $args ) {

    // Add first/last classes to nested menu items
    $ids        = array();
    $parent_ids = array();
    $top_ids    = array();
    foreach ( $objects as $i => $object ) {
        // If there is no menu item parent, store the ID and skip over the object
        if ( 0 == $object->menu_item_parent ) {
            $top_ids[$i] = $object;
            continue;
        }

        // Add first item class to nested menus
        if ( ! in_array( $object->menu_item_parent, $ids ) ) {
            $objects[$i]->classes[] = 'first-menu-item';
            $ids[]          = $object->menu_item_parent;
        }

        // If we have just added the first menu item class, skip over adding the ID
        if ( in_array( 'first-menu-item', $object->classes ) )
            continue;

        // Store the menu parent IDs in an array
        $parent_ids[$i] = $object->menu_item_parent;
    }

    // Remove any duplicate values and pull out the last menu item
    $sanitized_parent_ids = array_unique( array_reverse( $parent_ids, true ) );

    // Loop through the IDs and add the last menu item class to the appropriate objects
    foreach ( $sanitized_parent_ids as $i => $id )
        $objects[$i]->classes[] = 'last-menu-item';

    // Finish it off by adding classes to the top level menu items
    $objects[1]->classes[] = 'first-menu-item'; // We can be assured 1 will be the first item in the menu :-)
    $objects[end( array_keys( $top_ids ) )]->classes[] = 'last-menu-item';

    // Return the menu objects
    return $objects;

}

Кредиты отправляются Томасу за публикацию решения.

0 голосов
/ 19 октября 2010

Вы всегда можете использовать селекторы jQuery :first и :last;)

0 голосов
/ 18 октября 2010

Как вы выводите его в свой шаблон? Меню добавляется через панель администратора или вручную в шаблон?

0 голосов
/ 15 октября 2010

Кодекс Wordpress содержит всю необходимую информацию.Но я предполагаю, что вы ищете функцию wp_nav_menu .Тем не мение;насколько я знаю;невозможно указать другой класс только для первого и последнего пунктов меню.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...