My DataTables View is not sorting properly
A DataTables View opens in the order set in its Sort by field and Sort direction settings, on the Filter & Sort tab of the View editor. Sorting results by field value explains those settings.
DataTables also remembers how a visitor last left each table, including the sort order, the page and the search. When the page loads again in the same browser tab, the table opens that way, so a table you sorted yourself can open in a different order from the one set in the View. Closing the tab clears what was remembered.
Turn it off for one View #
Uncheck Save Table State on the View editor’s DataTables tab, then update the View. The table then opens in the View’s own order every time. The Save Table State article shows where the setting is.
Open a View once without what was remembered #
Add ?cache to the end of the View’s address. For example, https://example.com/view/datatables-sort/ becomes https://example.com/view/datatables-sort/?cache. The next time the page loads without ?cache, the remembered order comes back.
Turn it off for every DataTables View #
To stop every DataTables View on the site from remembering how visitors left it, add this code:
/**
* Stops DataTables from remembering how each visitor left a table, so every
* DataTables View opens in the sort order set in the View.
*
* @param array $dt_config The DataTables configuration for the View.
*
* @return array The modified configuration.
*/
add_filter( 'gravityview_datatables_js_options', function ( $dt_config ) {
$dt_config['stateSave'] = false;
return $dt_config;
} );Read here how to add these code samples to your website: Where to put code samples.
Tables that switched to oldest first after an update #
An earlier version of the code above also set order to an empty array. On DataTables 3.0 to 3.13.2, that line made tables using the Ajax (Server-side) processing mode skip the View’s sort and list the newest entries first. From DataTables 3.14.0, those tables follow the View’s settings, so a View set to Ascending lists its oldest entries first. To list the newest entries first, set Sort direction to Descending in the View.