Support » Fixing WordPress » Removing a comma from the last <li> item

  • Hello,

    I would be really grateful if someone could help me out with some code I am working on. I am relatively new to WordPress and PHP so please excuse my ingnorance.

    I am looking for a solution to remove the comma from the last list item in a function that generates a list of all the categories a post appears in (minus a few admin categories).

    the function is as follows:

    foreach((get_the_category()) as $cat) {
    if ($cat->cat_ID != '1') // Uncategorised
    if ($cat->cat_ID != '3') // cities
    if ($cat->cat_ID != '10') // states
    if ($cat->cat_ID != '57') // _hero
    if ($cat->cat_ID != '56') // _alsofeatured
    echo("<li><a href=\"" . get_category_link($cat->cat_ID) . "\">" . $cat->cat_name . "</a>,</li>");

    as you can see the list could be any length, from one item to fifty etc, so I need a solution to count the number of items generated and remove the , at the end of the list tag on the final one.

    Does anyone know of a simple way to do this?

    Thanks for your help in advance.

    Warm Regards

    Alex McGibbon
    Prettier Pixels

Viewing 3 replies - 1 through 3 (of 3 total)
  • I think you can use a parameter to exclude certain categories and clean up this code a bit 🙂

    Look here:



    Forum Moderator

    @doublejosh: Unless I’m mistaken, wp_list_categories is better suited to a side bar. It will display all categories on the site – not a list of categories associated with a single post. What seems to be needed here is a replacement for the_category that allows for specific categories to be excluded from the displayed list.

    @alex: Off the top of my head and untested:

    $my_cats = array();
    $my_unwanted = array('1','3','10','56','57');
    foreach((get_the_category()) as $cat) {
    	if(!in_array($cat->cat_ID,$my_unwanted) $my_cats[] = '<a href="' . get_category_link($cat->cat_ID) . '">' . $cat->cat_name . '</a>';
    $commas = count($my_cats) -1;
    $count = 0;
    foreach($my_cats[] as $my_cat) {
    	echo '<li>'.$my_cat;
    	if($count <= $commas) echo ',';
    	echo '</li>';

    Here’s how to add a first and last class to page listings. This might be useful for categories too…

    <!-- MAIN MENU -->
    	function add_fl_class($input) {
    		if( !empty($input) ) {
    			$items= explode( "\n", $input );
    			$items[0]= str_replace("<li class=\"", "<li class=\"first ", $items[0]);
    			$items[count($items)-1]= str_replace("<li class=\"", "<li class=\"last ", $items[count($items)-1]);
    			$o= '';
    			foreach( $items as $i ) {
    				$o.= $i;
    		echo $o;
    	add_last_class( wp_list_pages('echo=0&depth=1&title_li=&orderby=id&show_images=0') );
    <!-- END MAIN MENU -->

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Removing a comma from the last <li> item’ is closed to new replies.