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
Jamie40
Forum Newbie
Posts: 4 Joined: Fri Nov 07, 2014 6:48 pm
Post
by Jamie40 » Sun Dec 07, 2014 3:37 pm
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?
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Sun Dec 07, 2014 6:24 pm
It's an array, not an object. Inside that array
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
Post
by Jamie40 » Sun Dec 07, 2014 6:33 pm
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.
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Sun Dec 07, 2014 7:53 pm
Use a foreach loop on the outer array,
then do ->slug.
Code: Select all
foreach ($categories as $category) {
$slug = $category->slug;