26

I am trying to retrieve the slug for a tag inside a wordpress post, now its possible to get all tag info using

$tag = wp_get_post_tags($post->ID);

More info on this on the Wordpress Docs

By using this you should get data returned like this...

Array
(
   [0] => stdClass Object
       (
           [term_id] => 4
           [name] => tag2
           [slug] => tag2
           [term_group] => 0
           [term_taxonomy_id] => 4
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 7
       )

   [1] => stdClass Object
       (
           [term_id] => 7
           [name] => tag5
           [slug] => tag5
           [term_group] => 0
           [term_taxonomy_id] => 7
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 6
       )

)

Now what I want is the slug for the first item which should be as follows

$tag[0]['slug']

However by doing so I recieve this php error:

Cannot use object of type stdClass as array

Can someone tell me what I'm doing wrong here? and whats the best way to get the slug data

Ian
  • 375
  • 2
  • 6
  • 10

2 Answers2

57

Note that the array contains objects (instances of stdClass), not other arrays. So the syntax is:

$tag[0]->slug
rid
  • 61,078
  • 31
  • 152
  • 193
  • Ah, thats exactly what I was looking for. Think I need to go back to php basics – Ian May 30 '11 at 02:11
  • Hi, instead of 'slug', I have '@classId' as the name to be fetched. Getting syntax error at token '@', do you know any work around? Thanks – mtk Jul 27 '12 at 17:29
  • fyi. I am calling a mysql proc with out parameter, and then doing a select in next query. – mtk Jul 27 '12 at 17:29
  • @mtk, use `$tag[0]->{"@classId"}`. – rid Jul 27 '12 at 17:36
  • @radu that didn't work. Have asked the same question [here](http://stackoverflow.com/questions/11693234/php-mysql-get-value-of-out-parameter-from-a-stored-proc). Please see. – mtk Jul 27 '12 at 18:04
3

Another option should be to explicitly cast $tag[0] into an array:

$t = (array)$tag[0];
$t["slug"] = ...

Can't get it to work though

itlunch
  • 69
  • 6
  • I created a custom walker for my menu in wordpress. Somehow it used both: **objects** and **arrays** in one argument. This little peace of code did the trick, didn't know about it. – Rens Tillmann Jan 13 '14 at 21:09