• Resolved figure2

    (@figure2)


    Greetings. I playing with a php function to display a list of up to 3 categories (Advertising, Design, Publishing) in a headline, with commas after all but the last category item. I figured out how to display the categories with commas but can’t figure out how to eliminate the comma after the last category item.

    Here are my PHP efforts so far:

    <h4>
    <?php $taxterms = get_the_terms($post->ID, 'portfolio_category' );
    $taxcount = count($taxterms);
    	if($taxcount == 1){
    		if ($taxterms)
    			foreach ($taxterms as $taxterm){
    				echo $taxterm->name . ' '; }
    	}else if($taxcount > 1){
    		if ($taxterms)
    			foreach ($taxterms as $taxterm){
    				 echo $taxterm->name . ', ';
    			}
    	}
    	?>
    </h4>

    Here is how it looks on the site: http://www.lcomdesigns.com/portfolio/teaching-the-levees/

    Any help eliminating that last comma is appreciated.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You could add the commas with css instead of php.

    If the count is greater than one, wrap each category in a span, and remove the comma output. Then add the commas in with css like so:

    h4 span:after {
    	content: ", ";
    }
    h4 span:last-of-type:after {
    	display: none;
    }
    Thread Starter figure2

    (@figure2)

    Thanks. I’ll give it a shot.

    Thread Starter figure2

    (@figure2)

    @alphaalec: Your method worked. Thanks.

    For anyone who is interested, this is my final code using the CSS above:

    <h4>
    <?php $taxterms = get_the_terms($post->ID, 'portfolio_category' );
    	$taxcount = count($taxterms);
    	if($taxcount == 1){
    		if ($taxterms)
    			foreach ($taxterms as $taxterm){
    				echo $taxterm->name;
    		}
    	}else if($taxcount > 1){
    		if ($taxterms)
    			foreach ($taxterms as $taxterm){
    				 echo '<span>' . $taxterm->name . '</span>';
    		}
    	}
     ?>
    </h4>

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘List categories as text in a headline, with commas’ is closed to new replies.