Automattic\WooCommerce\Internal\ProductFilters

TaxonomyHierarchyData::build_full_hierarchy_mapprivateWC 1.0

Build hierarchy map for FilterData and ProductFilterTaxonomy.

Pre-computes descendants and ancestor chains for maximum query speed.

Method of the class: TaxonomyHierarchyData{}

No Hooks.

Returns

Array. Complete hierarchy map with descendants and ancestor chains.

Usage

// private - for code of main (parent) class only
$result = $this->build_full_hierarchy_map( $taxonomy ): array;
$taxonomy(string) (required)
The taxonomy name.

TaxonomyHierarchyData::build_full_hierarchy_map() code WC 10.3.3

private function build_full_hierarchy_map( string $taxonomy ): array {
	$terms = get_terms(
		array(
			'taxonomy'   => $taxonomy,
			'hide_empty' => false,
			'orderby'    => 'name',
			'order'      => 'ASC',
		)
	);

	if ( is_wp_error( $terms ) || empty( $terms ) ) {
		return array();
	}

	$map = array(
		'descendants' => array(), // term_id => [descendant_ids].
		'ancestors'   => array(), // term_id => [ancestor_ids].
		'tree'        => array(),
	);

	// Build core lookups and temporary structures.
	$temp_children = array();
	$temp_parents  = array();
	$temp_terms    = array();

	foreach ( $terms as $term ) {
		$term_id   = $term->term_id;
		$parent_id = $term->parent;

		$temp_parents[ $term_id ] = $parent_id;

		if ( ! isset( $temp_children[ $parent_id ] ) ) {
			$temp_children[ $parent_id ] = array();
		}

		$temp_children[ $parent_id ][] = $term_id;

		$temp_terms[ $term_id ] = array(
			'slug'    => $term->slug,
			'name'    => $term->name,
			'parent'  => $parent_id,
			'term_id' => $term->term_id,
		);
	}

	// Pre-compute descendants and ancestors.
	foreach ( array_keys( $temp_parents ) as $term_id ) {
		$map['descendants'][ $term_id ] = $this->compute_descendants( $term_id, $temp_children );
		$map['ancestors'][ $term_id ]   = $this->compute_ancestors( $term_id, $temp_parents );
	}

	foreach ( $temp_children[0] as $term_id ) {
		$this->build_term_tree( $map['tree'], $term_id, $temp_children, $temp_terms );
	}

	return $map;
}