Page 1 of 1

Help working with Objects

Posted: Sun Dec 07, 2014 3:37 pm
by Jamie40
I am working in WordPress and I am trying to get some information into a variable. I am trying to get the names of categories. So I do this

Code: Select all

$categories = get_categories();
var_dump($categories);
The above returns this

Code: Select all

     array(15) {
  [4]=>
  object(stdClass)#369 (15) {
    ["term_id"]=>
    &string(3) "191"
    ["name"]=>
    &string(11) "Band member"
    ["slug"]=>
    &string(11) "band-member"
    ["term_group"]=>
    string(1) "0"
    ["term_taxonomy_id"]=>
    string(3) "192"
    ["taxonomy"]=>
    string(8) "category"
    ["description"]=>
    &string(0) ""
    ["parent"]=>
    &string(1) "0"
    ["count"]=>
    &string(1) "4"
    ["cat_ID"]=>
    &string(3) "191"
    ["category_count"]=>
    &string(1) "4"
    ["category_description"]=>
    &string(0) ""
    ["cat_name"]=>
    &string(11) "Band member"
    ["category_nicename"]=>
    &string(11) "band-member"
    ["category_parent"]=>
    &string(1) "0"
  }
so then I thought that I would be able to do this

Code: Select all


$slug = $categories->slug;
echo $slug;
But when I do that, I get an error, "Trying to get property of non object".

What am I doing wrong?

Re: Help working with Objects

Posted: Sun Dec 07, 2014 6:24 pm
by requinix

Code: Select all

array(15) {
It's an array, not an object. Inside that array

Code: Select all

[4]=>
  object(stdClass)#369 (15) {
is an object.

The problem is that array(15) and [4] which means you don't just simply get "the" slug. There are 15 of them - do you want them all or just a particular one?

Re: Help working with Objects

Posted: Sun Dec 07, 2014 6:33 pm
by Jamie40
I want to be able to get all of them so that I can switch through them to load a particular template based on the category slug.

Re: Help working with Objects

Posted: Sun Dec 07, 2014 7:53 pm
by requinix
Use a foreach loop on the outer array, then do ->slug.

Code: Select all

foreach ($categories as $category) {
    $slug = $category->slug;