Skip to content

Commit

Permalink
changed sorting to take into account empty sortable values
Browse files Browse the repository at this point in the history
We've reworked this code to work correctly with empty sortable values. Now images with filled values ​​will be sorted first. And empty images will be inserted later at the very end of the array.
  • Loading branch information
Fellan-91 committed Apr 26, 2024
1 parent 2c5da0b commit fc56c86
Showing 1 changed file with 36 additions and 11 deletions.
47 changes: 36 additions & 11 deletions classes/class-get-portfolio.php
Original file line number Diff line number Diff line change
Expand Up @@ -1367,19 +1367,43 @@ public static function get_query_params( $options, $for_filter = false, $layout_
case 'image_caption':
case 'image_alt':
case 'image_description':
$sort_tmp = array();
$new_images = array();
/**
* We've reworked this code to work correctly with empty sortable values.
* 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;
} else {
$sort_tmp[ $key ] = $ma[ $custom_order ];
}
}

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

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

array_multisort( $sort_tmp, $images );
foreach ( $images as &$ma ) {
$new_images[] = $ma;
// Append empty elements at the end of the sorted array.
foreach ( $empty_elements as $empty_element ) {
$new_images[] = $empty_element;
}

$images = $new_images;
// Assign the sorted images back to the original variable.
$images = array_values( $new_images );
break;
case 'rand':
// We don't need to randomize order for filter,
Expand All @@ -1396,11 +1420,12 @@ public static function get_query_params( $options, $for_filter = false, $layout_
}
}

if ( 'desc' === $custom_order_direction ) {
$images = array_reverse( $images );
}

break;
}
if ( 'desc' === $custom_order_direction ) {
$images = array_reverse( $images );
}
}

// pages count.
Expand Down

0 comments on commit fc56c86

Please sign in to comment.