5

I have the following line of code: $terms = get_the_terms( $the_post->ID, 'posts_tags' ); echo $terms; The idea is to echo out the array in the format of the tags but instead it just returns the word Array?

How do I do this? The tags should be presented like this: 'tag1, tag2, tag3'

3 Answers 3

9

try

foreach($terms as $term){
    echo $term;
}

you might want to add something to separate them, like a $echo "," or something, but you get the idea
You can also use this

$termsString = implode (',' , $terms);
echo $termsString;

As requested:

The terms is indeed an array, see for instance @ProdigySim 's answer for how it looks. You could indeed print them for debuggin purposes with var_dump or print_r, but that would not help you in a production environment.

Assuming that it is not an associative array, you could find the first tag like this:

echo $terms[0]

and the rest like

echo $terms[1]

Right up until the last one (count($terms)-1).
The foreach prints each of these in order. The second, as you can find in the manual just makes one string of them.

In the end, as you asked in the comments: Just paste this.

$terms = get_the_terms( $the_post->ID, 'posts_tags' ); 
$termsString = implode (',' , $terms);
echo $termsString;
Sign up to request clarification or add additional context in comments.

9 Comments

This is correct. You might explain that $terms is an Array, and can't be directly echo'd.
I thought cameron already had that in the question, but I can add something
Sorry, I wasn't clear. Cameron knows it's an Array, but not that it can't be used as such. No big.
Okay I'm not getting this :/ Could you show the code in full as I'm just not following. Thanks.
Just past the second code instead of the echo $terms. I'll post a "complete" example, but you didn't give me much to work with...
|
5

You're looking for print_r()

$a = array ('a' => 'apple', 'b' => 'banana');
print_r ($a);

outputs

Array
(
    [a] => apple
    [b] => banana
)

1 Comment

Cameron said he wanted to display the items like "item, item, item", so he is actually looking for a method that will iterate over the array, and display the terms with formatting.
1

Arrays are an amazing feature in every programming language I've ever used. I highly suggest spending some time reading up on them, especially if you're customizing wordpress.

The reason it only echos array is because echo can only return strings. Try print_r($terms) or var_dump($terms) for more information.

http://php.net/manual/en/language.types.array.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.