Phew! Bit more complex than I would’ve liked – if only the filter page_css_class
passed back $args
it would save a lot of effort (may submit this to trac).
Since 3.3 it’s as easy as this!
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 );
For those on pre WordPress 3.3, here’s the workhorse:
/**
* 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') );
}
}
I’d advise placing the class in your functions.php
, then it’s available wherever you’d like to use it.
To use it, call wp_list_pages()
like so;
// 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' => ''
));