WP_Query loop: incorrect sort order with AJAX filters
A custom loop with AJAX filters sorted posts correctly for one post type and incorrectly for another. The query arguments were the same, which was a mystery at first. The culprit turned out to be a plugin that changes the order of posts for the post types it manages.
Problem: A filtered archive page re-runs a WP_Query through AJAX with custom sort parameters, but for one post type the results come back in the wrong order: the orderby argument seems to be ignored.
Step 1. Check the query arguments
First make sure the loop gets the arguments you think it gets. Log them right before the query runs:
$args = array(
'post_type' => 'portfolio',
'orderby' => 'date',
'order' => 'DESC',
);
// Debug: write the final arguments to wp-content/debug.log (remove afterwards).
error_log( print_r( $args, true ) );
$query = new WP_Query( $args );
With WP_DEBUG_LOG enabled, the arguments appear in wp-content/debug.log. In an AJAX handler this is the easiest way to see them, because you can’t print anything to the page.
To see the actual SQL, log $query->request after the query runs. If the ORDER BY clause there differs from your arguments, something changes the query on the way.
Step 2. Check plugins that change the post order
If the arguments are right, look at the installed plugins. Intuitive Custom Post Order and similar drag-and-drop ordering plugins change the order of posts for the post types they are enabled for, by modifying the queries on those post types. That explains why one post type sorted correctly and the other didn’t: ordering was enabled only for the second one.
wp plugin list --status=active | grep -i order
Fix: disable ordering for that post type
You don’t have to deactivate the whole plugin. In my case it was enough to turn off sorting for the affected post type in Settings → Intuitive CPO. The drag-and-drop order keeps working for the other post types, and your own orderby works for this one.
NOTE: A quick way to confirm that a plugin causes the problem is to deactivate it temporarily and test the query again. If the sort becomes correct, that plugin is responsible; then look in its settings for a per-post-type option instead of leaving it disabled.