WordPress.org

Support

Support » Themes and Templates » wp_list_pages add class on <li>

wp_list_pages add class on <li>

  • I am working on a site that requires my horizontal nav have pipe ( “|” ) between the items. I am using wp_list_pages to create the menu and I am applying the pipe characters using css border:right, etc. My problem is that I do not want a border on my final list element. Could someone please show me code to add classes to the first and/or last <li>or anchor tags generated by wp_list_pages? thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • Wanted to bump this thread, since I’m having the same problem.

    Can anyone offer advice?

    #navigationMenu li {
    	display: inline;
    	/* Add the pipe character "|" after each page link */
    	border-right: 1px solid #CCC;
    }

    Try adding something like this in your theme’s functions.php. It will add first and last classes to the list items.

    add_filter('wp_list_pages','wp_list_pages_add_first_last');
    
    function wp_list_pages_add_first_last($content) {
    	$content = preg_replace('/li class\=\"/', 'li class="first ', $content, 1);
    	$content_rev = strrev($content);
    	$content_rev = preg_replace('/\"\=ssalc il/', ' tsal"=ssalc il', $content_rev, 1);
    	return strrev($content_rev);
    
    }

    You don’t need to make it that complicated surely….

    Either use the CSS2 :last-child, obviously users not on CSS2 compliant browsers won’t have the CSS def applied…

    Or if you have a set amount of items in the list and you know how many LI elements there will be you could do the following…

    #yourID li+li+li+li {border-right:none}
    If the forth LI element
    #yourID li+li+li+li+li {border-right:none}
    If the fifth LI element

    and so on….

    Failing those, you’d need something like Alex suggested…

    alexdunae: this is brilliant, thanks for this. My menu is working like a charm with the seperator after each item except for the last one.

    Cheers…

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘wp_list_pages add class on <li>’ is closed to new replies.
Skip to toolbar