matt
matt

Reputation: 44393

PHP & Wordpress: print array content

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;
    }
}

Upvotes: 2

Views: 26160

Answers (6)

Aman Maurya
Aman Maurya

Reputation: 1325

Function using the wp_parse_args system to manage its single $args argument, which could be given whatever values you wanted. In this case $args stores detailed display overrides, a pattern found in many WordPress functions.

$args = wp_parse_args( $args, $term->name );
echo $arg[157]['term_id']; //output 157
echo $arg[157]['name'];  //output Entertainment

works fine for me more detail

http://codex.wordpress.org/Function_Reference/wp_parse_args

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 132051

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;

Upvotes: 3

Zagor23
Zagor23

Reputation: 1963

print_r ($terms[7]->slug) looks logical to me, since it's an array of objects

UPDATE

Since you are unsure how many items get_event_term should return, you should return an Array.

function get_event_term($post) {
    $aReturn = array();
    $terms = get_the_terms( (int) $post->ID, 'event_type' );
    if ( !empty( $terms ) ) {
        print_r($terms);
        foreach($terms as $term){ // iterate through array of objects
            $aReturn[] = $term->slug; // get the property that you need
        }
    }
    return $aReturn;
}

Upvotes: 0

Peter Adrian
Peter Adrian

Reputation: 297

Or, to complicate things a little bit:

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

Upvotes: 2

Riz
Riz

Reputation: 10246

Try this.

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

Upvotes: 0

Gntem
Gntem

Reputation: 7165

try

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

you object stdclass is in array[7] offset.

Upvotes: 2

Related Questions