Automattic\WooCommerce\Blocks\BlockTypes

ProductFilterTaxonomy::sort_terms_by_criteriaprivateWC 1.0

Sort terms by the specified criteria (name or count).

Method of the class: ProductFilterTaxonomy{}

No Hooks.

Returns

Array. Sorted terms.

Usage

// private - for code of main (parent) class only
$result = $this->sort_terms_by_criteria( $terms, $orderby, $order, $taxonomy_counts ): array;
$terms(array) (required)
Array of term objects to sort.
$orderby(string) (required)
Sort field (name, count, menu_order).
$order(string) (required)
Sort direction (ASC, DESC).
$taxonomy_counts(array) (required)
Context-aware term counts.

ProductFilterTaxonomy::sort_terms_by_criteria() code WC 10.3.6

private function sort_terms_by_criteria( array $terms, string $orderby, string $order, array $taxonomy_counts ): array {
	$sort_order = 'DESC' === strtoupper( $order ) ? -1 : 1;

	usort(
		$terms,
		function ( $a, $b ) use ( $orderby, $sort_order, $taxonomy_counts ) {
			$a = (object) $a;
			$b = (object) $b;
			switch ( $orderby ) {
				case 'count':
					$count_a    = $taxonomy_counts[ $a->term_id ] ?? 0;
					$count_b    = $taxonomy_counts[ $b->term_id ] ?? 0;
					$comparison = $count_a <=> $count_b;
					break;

				case 'name':
				default:
					$comparison = strcasecmp( $a->name, $b->name );
					break;
			}

			return $comparison * $sort_order;
		}
	);

	return $terms;
}