Custom query filter for order by is causing issue with group by in wordpress

If your custom query filter for ORDER BY is causing issues with GROUP BY in WordPress, it’s likely due to how MySQL handles GROUP BY in relation to ORDER BY. Here’s how you can fix it:

Common Issue

When you use GROUP BY in a WordPress custom query and try to sort it with ORDER BY, MySQL may throw an error like:

“Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column.”

This happens because MySQL’s STRICT mode enforces that the ORDER BY clause must contain columns from the GROUP BY clause or use aggregate functions like MAX(), MIN(), etc.

Solutions

1. Use Aggregate Functions

Modify your ORDER BY to use an aggregate function, such as:

ORDER BY MAX(meta_value) DESC

Example in WP_Query:


$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'fields' => 'ids',
);
$query = new WP_Query($args);

2. Modify GROUP BY with ORDER BY Using ANY_VALUE()

If using MySQL 5.7+ with STRICT mode enabled, wrap the non-grouped column in ANY_VALUE().

Example:


global $wpdb;
$results = $wpdb->get_results("
SELECT post_id, ANY_VALUE(meta_value) as price
FROM $wpdb->postmeta
WHERE meta_key = 'price'
GROUP BY post_id
ORDER BY price DESC
");

3. Disable ONLY_FULL_GROUP_BY Mode

If you’re on a local or test environment, you can disable ONLY_FULL_GROUP_BY in MySQL:


SET sql_mode = ''
or
SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));

⚠ Caution: This is not recommended on production servers unless necessary.

4. Ensure Consistency Between GROUP BY and ORDER BY Columns

Make sure all ORDER BY columns are also in GROUP BY.

Example:


$results = $wpdb->get_results("
SELECT post_id, meta_key, MAX(meta_value) as price
FROM $wpdb->postmeta
WHERE meta_key = 'price'
GROUP BY post_id, meta_key
ORDER BY price DESC
");

Final Thoughts

Best Approach: Use MAX() or ANY_VALUE() when necessary.

For Complex Queries: Consider running two separate queries—one to get grouped results, another for ordering.
Avoid Disabling STRICT Mode unless it’s a last resort.

Related Posts


How to Fix Empty href Tags When Displaying Custom Tag Cloud as a List in WordPress

Fixing empty href tags in a custom tag cloud displayed as a list in WordPress usually involves ensur...

How to Add a Logout Button Under an ‘Account’ Parent Menu in WordPress

Here’s a complete guide to adding a logout link as a dropdown item under an “AccountR...

Customize WordPress User Approval Emails Without Plugins (Step-by-Step Guide)

Customizing WordPress user approval emails without plugins involves using WordPress’s built-in...

Elementor Missing Features? Here’s How I Added a 5-Post Tile News Section Manually

Elementor is a powerful page builder, but sometimes its built-in widgets might not offer the exact l...

Recent Posts