Support » Themes and Templates » wp_list_pages() Even/Odd function

  • Hi, Im looking for a way to add a different classes to even an od items under a page listing, so I can make an alternating background effect in my sidebar.

    How can I do it?

Viewing 2 replies - 1 through 2 (of 2 total)
  • anabelle,
    A possible solution is pasted below. Please note that this will only show “top level” pages. No child pages will display in the results. Just copy and paste the following code into your themes functions.php file:

    add_filter( 'wp_list_pages', 'mf_striped_page_filter' );
    function mf_striped_page_filter( $content ){
    	if( !empty($content) )
    		$lines = explode( "\n", $content );
    	$findme = '<li class="';
    	$replace = $findme . 'stripe ';
    	$count = 1;
    	foreach( (array)$lines as $k => $l ){
    		if( 0 === strpos( $l, $findme ) ){
    			if( $count % 2 == 0 )
    				$l = substr_replace( $l, $replace, 0, strlen( $findme ) );
    			$o .= "\n" . $l;
    	return $o;

    This function will add a class of “stripe” to all <li> elements generated by wp_list_pages that are “top level”.

    this is some nice work mfields – I’ve never really played around with the hooks and filters much, but I started to after I saw this.

    Could this be modified so that unordered lists alternate background color? It looks like you’d replace ‘the wp_list_pages’ with ‘the_content’, but I’m not sure where your getting the $content and $lines from…

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘wp_list_pages() Even/Odd function’ is closed to new replies.