Alicia St Rose
asked on
Need to get rid of extra space between term and comma in foreach loop!
Hi!
I've got foreach loops going for custom post type taxonomy terms. The code I'm using adds a comma between terms, but not after the final term. I've got it working, however, there is a space between term and comma. I can't figure out how to remove it.
Here's my code:
I've got foreach loops going for custom post type taxonomy terms. The code I'm using adds a comma between terms, but not after the final term. I've got it working, however, there is a space between term and comma. I can't figure out how to remove it.
Here's my code:
<?php
$terms = wp_get_object_terms($post->ID,'grade-level');
// init counter
$i = 1;
if( $terms ): ?>
<strong>Grade: </strong>
<?php foreach( $terms as $term ): ?>
<?php // Get the term link
if( $term->count > 0 )
// display link to term archive
echo '<a href="' . get_term_link($term->slug, 'grade-level') . '">' . $term->name .'</a>'; ?>
<?php // Add comma (except after the last theme)
echo ($i < count($terms))?"," : "";
// Increment counter
$i++; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php
$terms = wp_get_object_terms($post->ID,'content-standard');
// init counter
$i = 1;
if( $terms ): ?>
<br>
<strong>CCSS: </strong>
<?php foreach( $terms as $term ): ?>
<?php // Get the term link
if( $term->count > 0 )
// display link to term archive
echo '<a href="' . get_term_link($term->slug, 'content-standard') . '">' . $term->name .'</a>'; ?>
<?php // Add comma (except after the last theme)
echo ($i < count($terms))?",":"";
// Increment counter
$i++; ?>
<?php endforeach; ?>
<?php endif; ?>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
How about populating an array and then using implode?
Something like this perhaps.
Something like this perhaps.
foreach( $terms as $term ) {
// add to array
$output[] = '<a href="' . get_term_link($term->slug, 'grade-level') . '">' . $term->name .'</a>, ';
}
// join output array with implode
$output = implode($output, ',');
echo $output;
ASKER
Once again, Julian saves the day!
Thanks!
Thanks!
Open in new window
to:Open in new window
If that doesn't work, perhaps you could provide a link to the live page so we can see the HTML being output?