Cameron
Cameron

Reputation: 28853

WordPress echo out array

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'

Upvotes: 5

Views: 26957

Answers (3)

Nanne
Nanne

Reputation: 64429

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;

Upvotes: 9

Ryre
Ryre

Reputation: 6181

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

Upvotes: 1

ProdigySim
ProdigySim

Reputation: 2933

You're looking for print_r()

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

outputs

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

Upvotes: 5

Related Questions