wp_list_pages() Even/Odd function (3 posts)

  1. anabelle
    Posted 8 years ago #

    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?

  2. Michael Fields
    Posted 8 years ago #

    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".

  3. brockangelo
    Posted 7 years ago #

    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...

Topic Closed

This topic has been closed to new replies.

About this Topic