I have a variable $cameramodel
which contains term meta of a wordpress taxonomy:
<?php
function cameramodel() {
$terms = get_the_terms($post->ID, 'camera');
$result = "";
foreach ($terms as $term) {
$term_id = $term->term_id;
$result .= get_term_meta( $term_id, 'model', true );
}
return $result;
}
$cameramodel = cameramodel(); ?>
On the front end I would echo $cameramodel
<?php echo $cameramodel; ?>
There are instances where $cameramodel
contains more than one value, but when I echo $cameramodel
, They all appear on one line with no spaces. My question is, how do I make a separator between each value? I want each value to be on it's own line, and I would like to be able to separate them with the word "and".
For example, if the variable contains "one two three" it currently prints "onetwothree", but what I want is:
one and
two and
three
Hope I am being clear.
Thanks!
If you are willing to edit the function slightly, I believe you will benefit from using an array and then joining it together into a string with the delimiter of your choice passed as an argument:
<?php
function cameramodel($delimiter) {
# Get the terms.
$terms = get_the_terms($post -> ID, "camera");
# Create an array to store the results.
$result = [];
# Iterate over every term.
foreach ($terms as $term) {
# Cache the term's id.
$term_id = $term -> term_id;
# Insert the term meta into the result array.
$result[] = get_term_meta($term_id, "model", true);
}
# Return the elements of the array glued together as a string.
return implode($delimiter, $result);
}
# Call the function using a demiliter of your choice.
$cameramodel = cameramodel(" and<br>");
?>
Of course, you can embed the delimiter you want in the function as the first argument of implode
instead of passing it as an argument.
Here is an example using the same logic.