0

I'm editing the category.php template and I need an array of current category child's.

I'm able to get an array with current category child's but there are too many keys, I'm using the following:

//get category ID                
$catego = get_category( get_query_var( 'cat' ) );
$cat_id = $catego->cat_ID;

//list current category childs
$catlist = get_categories(
            array(
            'child_of' => $cat_id,
            'orderby' => 'id',
            'order' => 'ASC'
) );

That gives me the following:

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 11
            [name] => test1
            [slug] => test1
            [term_group] => 0
            [term_taxonomy_id] => 11
            [taxonomy] => category
            [description] => 
            [parent] => 10
            [count] => 3
            [filter] => raw
            [cat_ID] => 11
            [category_count] => 3
            [category_description] => 
            [cat_name] => test1
            [category_nicename] => test1
            [category_parent] => 10
        )

    [1] => WP_Term Object
        (
            [term_id] => 12
            [name] => test2
            [slug] => test2
            [term_group] => 0
            [term_taxonomy_id] => 12
            [taxonomy] => category
            [description] => 
            [parent] => 10
            [count] => 1
            [filter] => raw
            [cat_ID] => 12
            [category_count] => 1
            [category_description] => 
            [cat_name] => test2
            [category_nicename] => test2
            [category_parent] => 10
        )

)

Now from this array I want to create an array which will only have the [cat_ID] key. I've tried the following but it gives me nothing ( http://php.net/manual/en/function.array-column.php ):

$category_id = array_column($catlist, '[cat_ID]');
print_r($category_id);

Any ideas? Thanks in advance.

1

Try this :

// This converts the WP_Term Object to array.
$catlist = json_decode(json_encode($catlist),true);

$category_id = array_column($catlist, 'cat_ID');
print_r($category_id);
  • @Mike You're welcome .. :) – Sumesh S Jun 21 '17 at 14:02
1

You can always use array_map()

$category_id = array();
$category_id = array_map( function ($data){
            return $data['cat_ID'];
        }, $catlist);

Or wordpress function:

   $category_id = array();
   $category_id =  wp_list_pluck( $catlist, 'cat_ID' );
  • +1 for wp_list_pluck() – darrinb Jun 15 '18 at 19:04
0

A foreach loop works:

$category_id = array();
foreach ($catlist as $cat){
    $category_id[] = $cat->cat_ID;
}
  • Nope, still nothing:( – Mike Jun 21 '17 at 13:49
  • How about the foreach @Mike – Senta Jun 21 '17 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.