PHP & Wordpress: print array content

21,993

Solution 1

Its an array of objects (even if it contains only a single entry at index "7"), not a single object

echo $terms[7]->slug;

With multiple "things

foreach ($terms as $term) echo $term->slug;

Solution 2

try

print_r($terms[7]->slug);

you object stdclass is in array[7] offset.

Solution 3

Or, to complicate things a little bit:

array_walk($terms, function($val,$key) use(&$terms){ 
    var_dump($val->slug);
});
Share:
21,993

Related videos on Youtube

matt
Author by

matt

Updated on January 23, 2020

Comments

  • matt
    matt about 4 years

    I'm to dumb right now …

    print_r($terms);
    

    does this …

    Array
    (
        [7] => stdClass Object
            (
                [term_id] => 7
                [name] => Testwhatever
                [slug] => testwhatever
                [term_group] => 0
                [term_taxonomy_id] => 7
                [taxonomy] => event_type
                [description] => 
                [parent] => 0
                [count] => 2
                [object_id] => 8
            )
    
    )
    

    How can I print the slug? I thought print print($terms->slug) should do the job, but it says: "Trying to get property of non-object"

    update:

    function get_event_term($post) {
        $terms = get_the_terms( (int) $post->ID, 'event_type' );
        if ( !empty( $terms ) ) {
            print_r($terms);
            return $terms[7]->slug;
        }
    }
    
  • matt
    matt almost 12 years
    Thank you, I updated my question. The problem is that this "7" is a dynamic number specifically for each post in wordpress. I have no idea what number it is. It doesn't seem to be the post->ID
  • Zagor23
    Zagor23 almost 12 years
    @matt Array $terms always has one element, or it could have more?
  • matt
    matt almost 12 years
    it could have more I guess. Normally it's set to one, but it is possible to add multiple terms to a post.