Automattic\WooCommerce\Blocks\BlockTypes

ProductCategories::build_category_tree()protectedWC 1.0

Build hierarchical tree of categories.

Method of the class: ProductCategories{}

No Hooks.

Return

Array.

Usage

// protected - for code of main (parent) or child class
$result = $this->build_category_tree( $categories, $children_only );
$categories(array) (required)
List of terms.
$children_only(true|false) (required)
Is the block rendering only the children of the current category.

ProductCategories::build_category_tree() code WC 8.9.0

protected function build_category_tree( $categories, $children_only ) {
	$categories_by_parent = [];

	foreach ( $categories as $category ) {
		if ( ! isset( $categories_by_parent[ 'cat-' . $category->parent ] ) ) {
			$categories_by_parent[ 'cat-' . $category->parent ] = [];
		}
		$categories_by_parent[ 'cat-' . $category->parent ][] = $category;
	}

	$parent_id = $children_only ? get_queried_object_id() : 0;
	$tree      = $categories_by_parent[ 'cat-' . $parent_id ]; // these are top level categories. So all parents.
	unset( $categories_by_parent[ 'cat-' . $parent_id ] );

	foreach ( $tree as $category ) {
		if ( ! empty( $categories_by_parent[ 'cat-' . $category->term_id ] ) ) {
			$category->children = $this->fill_category_children( $categories_by_parent[ 'cat-' . $category->term_id ], $categories_by_parent );
		}
	}

	return $tree;
}