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: the sort order, the page, and the number of entries shown. 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. The same View opened in a new tab opens in its own order.
Turn it off for one View #
Turn off Save Table State on the DataTables tab of the View’s settings, then click Update. 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;
} );Note: Not sure where to add the code? See Where to put code samples.
Tables that switched to oldest first after an update #
An older version of the code above also set order to an empty array. That line no longer changes the order: the table follows the View’s Sort by field and Sort direction, so a View with the default Sort by field and Ascending lists its oldest entries first. To list the newest entries first, set Sort direction to Descending in the View.