Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress echo out array

Tags:

php

wordpress

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'

like image 845
Cameron Avatar asked Dec 09 '22 10:12

Cameron


2 Answers

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;
like image 162
Nanne Avatar answered Dec 20 '22 19:12

Nanne


You're looking for print_r()

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

outputs

Array
(
    [a] => apple
    [b] => banana
)
like image 43
ProdigySim Avatar answered Dec 20 '22 19:12

ProdigySim