• Resolved regme

    (@regme)


    Hi!
    I want to get all subcategories of parent category
    How i think to do it:
    1. Get ParentID with no metter if I am in Sub or Parent cat:

    
    $category = get_the_category();
    $hierarchy = array_reverse( get_ancestors( $category[0]->term_id, 'category' ) );
    $hierarchy[] = $category[0]->term_id;
    $parent_id=$hierarchy[0];
    

    2. Now when i have parent id, i can get arrays with subcat
    $all_cats[]=( get_terms(array('category'),array('child_of' => $categories)));

    3. How to extrac only IDs of subcategories [‘term_id’] + parent ID?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi,
    Arrays with subcategories are actually WP_Term objects and you could iterate through these with “foreach”,
    Starting from your “$all_cats” variable you could use this:

    foreach ($all_cats as $cat) {
    	// echo 'Cat obj: '; print_r($cat);
    	foreach ($cat as $kcat) {
    		// echo 'K Cat: '; print_r($kcat);
    		$kterm = get_term( $kcat );
    		$kid = $kterm->term_id;
    		$kslug = $kterm->slug;
    		echo 'Kid: '.$kid.' KSlug: '.$kslug.' | ';
    	}
    }

    Cheers!

    Moderator bcworkz

    (@bcworkz)

    You wish to extract the term IDs of all returned term objects, correct?

    If you have no need of other object data aside from ID, use the ‘fields’ argument of get_terms() to only return an array of IDs instead of term objects. If only IDs:

    array('child_of' => $categories,
       'fields' => 'ids')

    If you need both the term ID and that of its parent, you can request ‘id=>parent’ as the fields parameter. print_r() the return to see how the return data is organized.

    If you have other needs for term object data, extract the IDs by looping through all the results and building a new array of just the ‘term_id’ values.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Get all IDs of subcategories’ is closed to new replies.