Skip to content

Commit

Permalink
simplified image custom sort code
Browse files Browse the repository at this point in the history
  • Loading branch information
nk-o committed Apr 30, 2024
1 parent fc56c86 commit 6068d13
Showing 1 changed file with 11 additions and 27 deletions.
38 changes: 11 additions & 27 deletions classes/class-get-portfolio.php
Original file line number Diff line number Diff line change
Expand Up @@ -1372,38 +1372,22 @@ 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.
*/
$sort_tmp = array();
$new_images = array();
$empty_elements = array();

// Separate empty elements from non-empty elements and sort non-empty elements.
foreach ( $images as $key => &$ma ) {
if ( empty( $ma[ $custom_order ] ) ) {
$empty_elements[ $key ] = $ma;
$non_empty_images = array();
$empty_images = array();
$sort_keys = array();

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

// Sort non-empty elements while preserving keys.
if ( 'desc' === $custom_order_direction ) {
arsort( $sort_tmp );
} else {
asort( $sort_tmp );
}

// Reorder the images array based on sorted keys.
foreach ( array_keys( $sort_tmp ) as $key ) {
$new_images[ $key ] = $images[ $key ];
}

// Append empty elements at the end of the sorted array.
foreach ( $empty_elements as $empty_element ) {
$new_images[] = $empty_element;
}
array_multisort( $sort_keys, 'desc' === $custom_order_direction ? SORT_DESC : SORT_ASC, $non_empty_images );

// Assign the sorted images back to the original variable.
$images = array_values( $new_images );
$images = array_merge( $non_empty_images, $empty_images );
break;
case 'rand':
// We don't need to randomize order for filter,
Expand Down

0 comments on commit 6068d13

Please sign in to comment.