I have an foreach to add terms to a post on WordPress Which is working great. Code below:
<h3>
<?php foreach($terms as $term) {?>
<?php echo $term->name;?>
<?php } ?>
</h3>
However I need to add a counter so that if there is more than one term in the <h3>
it adds a / between them. For instance:
<h3>Term Name</h3>
<h3>Term Name / Term Name / Term Name</h3>
This is the code I have so far however its not working.
<?php
$i = 1;
foreach($terms as $term) {
if($i == 1){
echo ' / '.$term->name;
} else {
echo $term->name;
}
$i++;
} ?>
You don’t need to use a counter. Just put each
$term->name
in to an array, and implode it:echo implode(' / ', array_map(function($term) { return $term->name; }, $terms));
Here’s a demo
Please try below code.
Here is the working solution 🙂