diff --git a/includes/classes/Feature/Facets/Widget.php b/includes/classes/Feature/Facets/Widget.php index 45e76fed40..5afc451aa9 100644 --- a/includes/classes/Feature/Facets/Widget.php +++ b/includes/classes/Feature/Facets/Widget.php @@ -135,7 +135,6 @@ public function widget( $args, $instance ) { $order = isset( $instance['order'] ) ? $instance['order'] : 'count'; $terms = Utils\get_term_tree( $terms, $orderby, $order, true ); - $term_tree = Utils\get_term_tree( $terms, 'count', 'desc', false ); $outputted_terms = array(); @@ -217,7 +216,7 @@ public function widget( $args, $instance ) { $flat_ordered_terms[] = $top_of_tree; - $to_process = $this->order_by_selected( $top_of_tree->children, $selected_filters['taxonomies'][ $taxonomy ]['terms'] ); + $to_process = $this->order_by_selected( $top_of_tree->children, $selected_filters['taxonomies'][ $taxonomy ]['terms'], $order, $orderby ); while ( ! empty( $to_process ) ) { $term = array_shift( $to_process ); @@ -225,7 +224,7 @@ public function widget( $args, $instance ) { $flat_ordered_terms[] = $term; if ( ! empty( $term->children ) ) { - $to_process = array_merge( $this->order_by_selected( $term->children, $selected_filters['taxonomies'][ $taxonomy ]['terms'] ), $to_process ); + $to_process = array_merge( $this->order_by_selected( $term->children, $selected_filters['taxonomies'][ $taxonomy ]['terms'], $order, $orderby ), $to_process ); } } @@ -316,12 +315,14 @@ public function widget( $args, $instance ) { /** * Order terms putting selected at the top * - * @param array $terms Array of terms - * @param array $selected_terms Selected terms + * @param array $terms Array of terms + * @param array $selected_terms Selected terms + * @param string $order The order to sort from. Desc or Asc. + * @param string $orderby The orderby to sort items from. * @since 2.5 * @return array */ - private function order_by_selected( $terms, $selected_terms ) { + private function order_by_selected( $terms, $selected_terms, $order = false, $orderby = false ) { $ordered_terms = []; $terms_by_slug = []; @@ -329,10 +330,7 @@ private function order_by_selected( $terms, $selected_terms ) { $terms_by_slug[ $term->slug ] = $term; } - ksort( $selected_terms ); - ksort( $terms_by_slug ); - - foreach ( $selected_terms as $term_slug => $nothing ) { + foreach ( $selected_terms as $term_slug ) { if ( ! empty( $terms_by_slug[ $term_slug ] ) ) { $ordered_terms[ $term_slug ] = $terms_by_slug[ $term_slug ]; } @@ -344,6 +342,30 @@ private function order_by_selected( $terms, $selected_terms ) { } } + if ( 'count' === $orderby ) { + if ( 'asc' === $order ) { + uasort( + $ordered_terms, + function( $a, $b ) { + return $a->count > $b->count; + } + ); + } else { + uasort( + $ordered_terms, + function( $a, $b ) { + return $a->count < $b->count; + } + ); + } + } else { + if ( 'asc' === $order ) { + ksort( $ordered_terms ); + } else { + krsort( $ordered_terms ); + } + } + return array_values( $ordered_terms ); }