I’m trying to create a shortcode that outputs my custom taxonomies, separated by a comma, but i want the last comma to be “en” instead of a comma. So like this:
taxonomy, taxonomy, taxonomy en taxonomy
So far i have this:
// Assortiment shortcode function verlichting_type( ){ $terms = get_the_terms( $post->ID, 'verlichting_type' ); foreach($terms as $term) { $entry_terms .= $term->name . ', '; } $entry_terms = rtrim( $entry_terms, ', ' ); return '<span class="verlichting__type"> ' . $entry_terms . ' </span>'; } add_shortcode( 'verlichting_type', 'verlichting_type' );
Advertisement
Answer
As I dont have an example of the $terms
or $entry_terms
variable I had to make up some dummy data, but I think you should be able to extract my example and place it into your code.
I made use of the ternary operator (https://www.php.net/manual/en/language.operators.comparison.php) to determine whether or not the final comma should be ‘,’ or ‘en’:
<?php function verlichting_type() { $entry_terms = ""; $terms = [ (object)['name' => 'taxonomy'], (object)['name' => 'taxonomy'], (object)['name' => 'taxonomy'], (object)['name' => 'taxonomy'] ]; echo '<span class="verlichting__type">'; foreach ( $terms as $index => $term) { $enIndex = sizeof($terms) - 2; $end = (isset($terms[$enIndex]) && $index == $enIndex ? ' en ' : ', '); $entry_terms .= $term->name . $end; } $entry_terms = rtrim( $entry_terms, ', ' ); return $entry_terms . '</span>'; }
This outputs:
<span class="verlichting__type">taxonomy, taxonomy, taxonomy en taxonomy</span>
This should work with any array length, e.g. if $terms
only has 2 elements:
<span class="verlichting__type">taxonomy en taxonomy</span>
Or 1 element:
<span class="verlichting__type">taxonomy</span>