• Hi.. i need a way to set class=”first” to the first element of the wp_list_pages

    Can someone help me out ?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Why don’t you just use the classes that are already there? You *can* add a class, if you must, but wp_list_pages already provides classes for each link. View your source code – it’s something like class="page_id_ID"

    Doodlebee’s right, you could use WP’s pre-existing class for this. The only drawback of that is that if you reorder your Pages so that a different Page comes first in the list, then whatever you were doing to the first item in the Page list before you’ll now be doing to a different item instead.

    To add a class of “first” to the first item in your Page list, whatever Page that happens to be, something like this should work:

    $page_list = wp_list_pages(‘title_li=&sort_column=menu_order&echo=0’);
    $page_list = preg_replace(‘class="page_item‘, ‘class=”first page_item’, $page_list, 1);
    echo $page_list;

    For the wp_list_pages() call in the first line of the above, just use whatever you’re already using with “&echo=0” added to the end of the parameters.

    – Tim

    Thread Starter steeler

    (@steeler)

    That works, thanks, though the preg_replace is preg_replace(‘class=”page_item’, ‘/class=”first page_item/’, $page_list, 1);

    Thanks ??

    Sorry, my code used backticks as delimiters, which the forum software here stripped out. Glad you worked out what needed tweaking to get it to work.

    – Tim

    hey,

    i had the same probleme, then i found a function in a thread, but it did not work, so i rewrote it and is works pretty well,

    i’m shure it could be imporved by comdining both regex into one, but still, it works pretty good

    function add_last_class($input) {
    	if( !empty($input) ) {
    
    		$pattern = '/<li class="/is';
    		$replacement = '<li class="first ';
    
    		$input = preg_replace($pattern, $replacement, $input);
    
    		$pattern = '/<li class="(?!.*<li class=")/is';
    		$replacement = '<li class="last ';
    
    		$input = preg_replace($pattern, $replacement, $input);
    
    		echo $input;
    	}
    }
    
    /* the echo=0 parma is important here */
    add_last_class(wp_list_categories('title_li=&echo=0'));

    hope it helps

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to set class to the first element of wp_list_pages’ is closed to new replies.