timholz
timholz

Reputation: 372

retrieve an array of id's from get_categories

I am trying to retrieve an array of ID's from:

$categories = get_categories(array('hide_empty' =>false,'taxonomy'=>'product_cat', 'child_of' => 15));

When i check $categories with var_dump, i get everything. But only the term_ID is needed.

I have tried the following foreach loop:

foreach ($categories as $category) {
                        $option = $category->cat_ID;
                        var_dump($option);
                      }

var_dump now shows:

int(16) int(37) int(41) int(42) int(17) int(38) int(29) int(40) int(30) int(31) int(32) int(33) int(34) int(36) 

I assume that this would be the desired array. How can i pass this array to a condition later on? theo

After much confusion i want to straighten up this question and post what worked for me:

<?php 
$categoryX = [];
$parentID = XX; //id of parent
$category = get_categories( array(

        'hide_empty' =>false,
        'taxonomy'=>'product_cat',
        'child_of' => $parentID 
        ) );

        foreach( $categoriySort as $category ) {
        array_push($categorySortiment, $category->cat_ID);
        } 
        array_push($categorySortiment, $parentID);

Then i can assign the variable $categoryX that holds an array with all the ID's to a condition later on.

Thanks for your help.

Upvotes: 1

Views: 3882

Answers (2)

GustavMahler
GustavMahler

Reputation: 687

The following declares a new array, then iterates through the categories adding the $category->cat_ID value to the $categoryIDArray using PHP's array_push() function. This results in an array containing just the category ID's.

  $categoryIDArray = [];

  foreach ($categories as $category) {
    array_push($categoryIDArray, $category->cat_ID);
  }

You can then simply pass the $categoryIDArray into whatever function you need like so:

$categories = getCategories( $categoryIDArray );

Upvotes: 1

Azad khan
Azad khan

Reputation: 79

$all_Categories = array(); foreach ($categories as $category) { $all_Categories = $category->cat_ID;}

Upvotes: 0

Related Questions