Issue with the way you are unsetting sticky posts from the $post_list
array and then reinserting them at the specified positions and should work correctly like below code structure.
Removed the unnecessary $position
variable in the foreach
loop.
Changed the way sticky items are inserted back into the $post_list array using array_unshift
to add them at the beginning of the array
function randomize_order_with_sticky_on_top( $post_list, $sort_view_id, $orderBy, $query ) {
shuffle( $post_list );
// Retrieve the sticky list for the current sort ID
$sticky_list = get_post_meta( $sort_view_id, '_sticky_data', TRUE );
if ( ! is_array( $sticky_list ) || count( $sticky_list ) < 1 ) {
return $post_list;
}
// Remove the sticky items from the $post_list
foreach ( $sticky_list as $object_id ) {
$index = array_search( $object_id, $post_list );
if ( $index !== false ) {
unset( $post_list[ $index ] );
}
}
// Reset array keys
$post_list = array_values( $post_list );
// Reinsert sticky items at the beginning of the $post_list
foreach ( $sticky_list as $object_id ) {
array_unshift( $post_list, $object_id );
}
return $post_list;
}