0

I'm a bit confused.

I have an array:

<?php 

$terms = get_the_terms($post->ID, 'pf');
        print_r($terms);
?>

And it outputs:

Array ( [15] => stdClass Object ( [term_id] => 15 [name] => Text [slug] => text [term_group] => 0 [term_taxonomy_id] => 33 [taxonomy] => pf [description] => An PF article. [parent] => 0 [count] => 3 [object_id] => 694 ) )

And I want just to output slug ("text" in this case) instead of the whole array.

So I'm doing:

<?php $terms = get_the_terms($post->ID, 'pf');
             echo $terms["slug"]; ?>

And it outputs nothing.

This gives no results as well:

echo "{$terms['slug']}";

Any ideas?

UPDATED!!!

I can't use $term[15]->slug since my script will be based on [taxonomy] (pf in this case)! :) So it's impossible to do that without foreach loop?

3 Answers 3

5

terms array 15 index contain object access like this

echo $term[15]->slug
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way of accessing $terms by "taxonomy" (pf in this case)? Because the ID may vary.
@meritum: ID will be vary you have to use foreach loop here. foreach($term as $object) { echo $object->slug; }
3

there is stdclass object at index 15 of the inside arry which can be converted/accessed as array by casting but try this insted

$term[15]->slug

Comments

-1

Following up on Pekka's answer, if you reformat your print_r() output, you'd get:

Array (
    [15] => stdClass Object (
        [term_id] => 15
        [name] => Text
        [slug] => text
        [term_group] => 0
        [term_taxonomy_id] => 33
        [taxonomy] => pf
        [description] => An PF article.
        [parent] => 0
        [count] => 3
        [object_id] => 694
    )
)

When dumping out a variable with print_r(), it's good practice to surround the call with <pre> tags - print_r doesn't do any HTML-ification of the data, so the nice indentation it does with arrays gets lost when viewed in an HTML page. Using the <pre> tags preserves the formatting. using var_dump() will do the same, but also add type/size data to the dump output.

2 Comments

I did not down voted but this does not answer OP's question anyway
At the time I wrote this, pekka's answer was still listed. However, he's now deleted it.

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.