<div class="menu"> <ul> <?php wp_list_pages('exclude=&title_li='); ?> </ul> </div>
создает следующий результат …
<div class="menu"> <ul> <li><a href="#">Page 1</a></li> <li><a href="#">Page with Subpages</a> <ul class="children"> <li><a href="#">Page with another subpage</a> <ul class="children"> <li><a href="#">subsubpage</a></li> </ul> </li> </ul> </li> <li><a href="#">Page 3</a></li> <li><a href="#">Page 4</a></li> </ul> </div>
На всех страницах с детьми применяется ul class="children"
. Можно ли создать любую функцию (или любой другой способ) для добавления имени класса на все страницы, в которых есть дети? В моем примере выше только «Страница с субстраницами» и первая страница «Страница с дочерней страницей» с другой подстраницей должна иметь li.parent
.
Возможно ли это на сервере? Я могу сделать это с помощью javascript, однако мне интересно, есть ли лучший и более чистый способ сделать это на сервере?
Спасибо
Уф! Бит более сложный, чем мне хотелось бы – если бы только фильтр page_css_class
передал обратно $args
это сэкономит много сил (может передать это trac).
Начиная с 3.3 это так же просто!
function add_parent_class( $css_class, $page, $depth, $args ) { if ( ! empty( $args['has_children'] ) ) $css_class[] = 'parent'; return $css_class; } add_filter( 'page_css_class', 'add_parent_class', 10, 4 );
Для тех, кто на pre WordPress 3.3, вот рабочая лошадка:
/** * Extend the default page walker class to append class names for pages that * are parents. * @uses Walker_Page */ class My_Page_Walker extends Walker_Page { /** * Filter in the classes for parents. */ function _filterClass( $class ) { $class[] = 'parent'; // change this to whatever classe(s) you require return $class; } /** * This is effectively a wrapper for the default method, dynamically adding * and removing the class filter when the current item has children. */ function start_el( &$output, $page, $depth, $args, $current_page ) { if ( !empty($args['has_children']) ) add_filter( 'page_css_class', array( &$this, '_filterClass') ); parent::start_el( $output, $page, $depth, $args, $current_page ); if ( !empty($args['has_children']) ) remove_filter( 'page_css_class', array( &$this, '_filterClass') ); } }
Я бы посоветовал разместить класс в ваших functions.php
, тогда он доступен везде, где вы хотели бы его использовать.
Чтобы использовать его, вызовите wp_list_pages()
следующим образом;
// You need to pass the walker argument to wp_list_pages(). You must use an // array to do this. wp_list_pages(array( 'walker' => new My_Page_Walker, 'title_li' => '' ));
Я думаю, что для этого есть более простое решение, вы можете добавить следующий фильтр в файл functions.php в папку темы. Вам не нужно ничего менять.
add_filter('page_css_class', 'check_parent', 10, 2 ); function check_parent($css_class, $page) { if (wp_list_pages("title_li=&child_of=".$page->ID."&echo=0")) array_push($css_class, "parent"); return $css_class; }
надеюсь, это поможет