Forcing numbers to sort properly

Let's say you have a drop-down field on your form with choices ranging from 1 to 10 or greater.

Dropdown field settings with numerical sorting for options 1 to 11

And you try to sort your View by this field:

Filter and sort settings showing primary and secondary sort options with ascending order selected

GravityView can't sort text-based fields as if they were numbers. So your View will probably appear like this, with the Order column not correctly sorted.

Table showing names with unsorted order values: Alice 1, Dan 10, Elliot 11, Bob 3, Charlie 9

There's a way to force GravityView to interpret those fields as if they were numbers by using a special filter:

add_filter( 'gk/gravityview/view/entries/query/sorting-parameters', function ( $params, $view ) {
    if ( '1' !== (string) $view->ID ) { // Change 1 to the View ID.
        return $params;
    }

    foreach ( $params as &$field ) {
        if ( '1' !== (string) $field['id'] ) { // Change 1 to the field ID that's numeric.
	    continue;
	}

        $field['is_numeric'] = true;
    }

    return $params;
}, 10, 2 );

Click here to see where to add this code snippet.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us