|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Gravity Perks // Entry Blocks // Multi Field Sorting |
| 4 | + * https://gravitywiz.com/documentation/gravity-forms-entry-blocks/ |
| 5 | + * |
| 6 | + * Mutli Field Sorting for GP Entry Blocks. |
| 7 | + * |
| 8 | + * Instruction Video: https://www.loom.com/share/b9867d2735d44519bf563961e9b30bd2 |
| 9 | + */ |
| 10 | +class GPEB_Multi_Field_Sorting { |
| 11 | + |
| 12 | + private $form_id; |
| 13 | + private $primary_sorting_field_id; |
| 14 | + private $secondary_sorting_field_id; |
| 15 | + private $sorting_direction; |
| 16 | + |
| 17 | + public function __construct( $config = array() ) { |
| 18 | + $this->form_id = rgar( $config, 'form_id' ); |
| 19 | + $this->primary_sorting_field_id = rgar( $config, 'primary_sorting_field_id' ); |
| 20 | + $this->secondary_sorting_field_id = rgar( $config, 'secondary_sorting_field_id' ); |
| 21 | + $this->sorting_direction = strtoupper( rgar( $config, 'sorting_direction', 'ASC' ) ); |
| 22 | + |
| 23 | + add_action( 'init', array( $this, 'init' ) ); |
| 24 | + } |
| 25 | + |
| 26 | + public function init() { |
| 27 | + add_filter( 'gpeb_queryer_entries', array( $this, 'sort_entries' ), 10, 2 ); |
| 28 | + } |
| 29 | + |
| 30 | + private function is_applicable_form( $current_form_id ) { |
| 31 | + return $current_form_id == $this->form_id; |
| 32 | + } |
| 33 | + |
| 34 | + public function sort_entries( $entries, $gf_queryer ) { |
| 35 | + if ( ! $this->is_applicable_form( $gf_queryer->form_id ) ) { |
| 36 | + return $entries; |
| 37 | + } |
| 38 | + |
| 39 | + usort( $entries, array( $this, 'sort_callback' ) ); |
| 40 | + |
| 41 | + return $entries; |
| 42 | + } |
| 43 | + |
| 44 | + private function sort_callback( $a, $b ) { |
| 45 | + $a_primary = rgar( $a, $this->primary_sorting_field_id, '' ); |
| 46 | + $b_primary = rgar( $b, $this->primary_sorting_field_id, '' ); |
| 47 | + |
| 48 | + $cmp = strcasecmp( $a_primary, $b_primary ); |
| 49 | + |
| 50 | + if ( $cmp === 0 && $this->secondary_sorting_field_id ) { |
| 51 | + $a_secondary = rgar( $a, $this->secondary_sorting_field_id, '' ); |
| 52 | + $b_secondary = rgar( $b, $this->secondary_sorting_field_id, '' ); |
| 53 | + $cmp = strcasecmp( $a_secondary, $b_secondary ); |
| 54 | + } |
| 55 | + |
| 56 | + return ( $this->sorting_direction === 'DESC' ) ? -$cmp : $cmp; |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +new GPEB_Multi_Field_Sorting( array( |
| 61 | + 'form_id' => 933, |
| 62 | + 'primary_sorting_field_id' => '1.6', |
| 63 | + 'secondary_sorting_field_id' => '1.3', |
| 64 | + 'sorting_direction' => 'ASC', // or 'DESC' |
| 65 | +) ); |
0 commit comments