Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions gp-populate-anything/gppa-sort-by-time-field.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
/**
* Gravity Perks // Populate Anything // Sort by Time Field
* https://gravitywiz.com/documentation/gravity-forms-populate-anything/
*
* Sort times chronologically when populating a Time field from Gravity Forms entries into a choice based field.
*
* Usage:
*
* 1. Install this code as a plugin or as a snippet.
* 2. Change your form and field ID below
*/
// Change `123` to your form ID and `4` to your populated field ID
add_filter( 'gppa_input_choices_123_4', function( $choices, $field, $objects, $field_values ){

usort( $choices, function( $a, $b ) {
$timeA = strtotime( $a['text'] );
$timeB = strtotime( $b['text'] );
return $timeA - $timeB;
});
Comment on lines +16 to +20
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle invalid time formats and strengthen comparator.
strtotime() returns false on unparseable strings, which casts to 0 and may scramble ordering. Also, returning raw subtraction can overflow on large timestamps. Consider validating timestamps and returning -1/0/1 explicitly. For example:

usort( $choices, function( $a, $b ) {
    $timeA = strtotime( $a['text'] );
    $timeB = strtotime( $b['text'] );
    if ( $timeA === false || $timeB === false ) {
        // Place unparsable entries at the end
        return $timeA === false && $timeB !== false
            ? 1
            : ( $timeA !== false && $timeB === false ? -1 : 0 );
    }
    return $timeA < $timeB ? -1 : ( $timeA > $timeB ? 1 : 0 );
});


return $choices;

}, 10, 4 );
Loading