Skip to content

Commit

Permalink
improved sort function
Browse files Browse the repository at this point in the history
  • Loading branch information
Fellan-91 committed May 14, 2024
1 parent cfdd706 commit 238ffc8
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions classes/class-get-portfolio.php
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,18 @@ public static function sort_by_field( &$array, $field, $order = 'desc' ) {
usort(
$array,
function ( $a, $b ) use ( $field, $order ) {
// Handle empty fields by placing them at the end of the array.
if ( empty( $a[ $field ] ) && empty( $b[ $field ] ) ) {
return 0; // Preserve the order of empty fields.
}
if ( empty( $a[ $field ] ) ) {
return 1; // Place empty a fields at the end.
}
if ( empty( $b[ $field ] ) ) {
return -1; // Place empty b fields at the end.
}

// Normal comparison.
return 'desc' === $order ? $b[ $field ] <=> $a[ $field ] : $a[ $field ] <=> $b[ $field ];
}
);
Expand Down Expand Up @@ -1381,20 +1393,7 @@ public static function get_query_params( $options, $for_filter = false, $layout_
* Now images with filled values ​​will be sorted first.
* And empty images will be inserted later at the very end of the array.
*/
$non_empty_images = array();
$empty_images = array();

foreach ( $images as $image ) {
if ( empty( $image[ $custom_order ] ) ) {
$empty_images[] = $image;
} else {
$non_empty_images[] = $image;
}
}

self::sort_by_field( $non_empty_images, $custom_order, $custom_order_direction );

$images = array_merge( $non_empty_images, $empty_images );
self::sort_by_field( $images, $custom_order, $custom_order_direction );
break;
case 'rand':
// We don't need to randomize order for filter,
Expand Down

0 comments on commit 238ffc8

Please sign in to comment.