Link to home
Start Free TrialLog in
Avatar of Alicia St Rose
Alicia St RoseFlag for United States of America

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.

User generated image
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; ?>

Open in new window

Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Perhaps change:
	  						echo '<a href="' . get_term_link($term->slug, 'grade-level') . '">' . $term->name .'</a>'; ?>

Open in new window

to:
	  						echo '<a href="' . get_term_link($term->slug, 'grade-level') . '">' . rtrim($term->name) .'</a>'; ?>

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?
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Norie
Norie

How about populating an array and then using implode?

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;

Open in new window

Avatar of Alicia St Rose

ASKER

Once again, Julian saves the day!

Thanks!