Help working with Objects

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Jamie40
Forum Newbie
Posts: 4
Joined: Fri Nov 07, 2014 6:48 pm

Help working with Objects

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Help working with Objects

Post 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?
Jamie40
Forum Newbie
Posts: 4
Joined: Fri Nov 07, 2014 6:48 pm

Re: Help working with Objects

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Help working with Objects

Post by requinix »

Use a foreach loop on the outer array, then do ->slug.

Code: Select all

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