Need to access sub-sub categories. So, I get the categories:

$terms = array(); $terms = get_categories(array('orderby' => 'name', 'hide_empty' => 0,'taxonomy' => 'category','parent' => 0)); if( ! $terms ) return null; if($first) { return $terms[0]->term_id; } 

So I get all the subcategories:

 $parrent_id = array(); $parrent_id = get_categories( ); foreach ($parrent_id as $value) { $sub_parent_id = $value->parent; if($sub_parent_id > 0){ $sub_parent_id = $value->term_id; } } 

How to get subcategories to these sub-categories that the script has received above?

  • Recursion will help you. And the primer :) - Sergey
  • How to implement it with a check for child_of?) - BonBonSlick

1 answer 1

Just in case with the tree. I can not imagine why we need a sub sub category without a tree.

 # # каТдая Π½ΠΎΠ΄Π° - ассоциативный массив, ΠΏΡ€Π΅Π΄ΡΡ‚Π°Π²Π»ΡΡŽΡ‰ΠΈΠΉ ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΡŽ ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ: # 'parent' => Ρ€ΠΎΠ΄ΠΈΡ‚Π΅Π»ΡŒΡΠΊΠ°Ρ Π½ΠΎΠ΄Π° # 'category' => катСгория # 'children' => массив Π½ΠΎΠ΄ ΠΏΠΎΠ΄-ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΉ ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΈ category # # получаСтся Π΄Π΅Ρ€Π΅Π²ΠΎ: # node - category # | # |- children[0] - (sub)category # | | # | |- children[0][0] - (sub)(sub)category # | # |- children[1] - (sub)category # # рСкурсивная функция Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠΈ ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΉ, Ρ‚ΠΎΡ‡Π½Π΅Π΅ ΡƒΠ·Π»ΠΎΠ² Π΄Π΅Ρ€Π΅Π²Π°, ΠΏΡ€Π΅Π΄ΡΡ‚Π°Π²Π»ΡΡŽΡ‰ΠΈΡ… ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΈ # $parent - ΠΈ Ρ‚Π°ΠΊ ясно # $maxdeep - максимальная Π³Π»ΡƒΠ±ΠΈΠ½Π°, Ρ‡Ρ‚ΠΎΠ±Ρ‹ Π½Π΅ Π³Ρ€ΡƒΠ·ΠΈΡ‚ΡŒ лишнСго function get_nodes($parent, $maxdeep) { $nodes = []; $parent_id = $parent == null ? 0 : $parent['category']->parent; $categories = get_categories(['parent' => $parent_id]); foreach ($categories as $category) { $node = [ 'parent' => $parent, 'category' => $category ]; $node['children'] = $maxdeep == 0 ? [] : get_nodes($node, $maxdeep - 1); $nodes[] = $node; } return $nodes; } $nodes = get_nodes(null, 3); # ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΈ foreach ($nodes as $node) { $category = $node['category']; # ΠΏΠΎΠ΄-ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΈ foreach ($node['children'] as $node) { $sub_category = $node['category']; # ΠΏΠΎΠ΄-ΠΏΠΎΠ΄-ΠΊΠ°Ρ‚Π΅Π³ΠΎΡ€ΠΈΠΈ foreach ($node['children'] as $node) { $sub_sub_category = $node['category'] } } }