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


Why WordPress Looks for .htaccess in the Wrong Directory When Using WP_HOME and WP_SITEURL

When you configure WP_HOME and WP_SITEURL in your WordPress wp-config.php file, especially when they...

How to Change the Active Link Color in Navigation Menu Using CSS: The Ultimate Guide

Having proper visual feedback in your website’s navigation is crucial for both user experience...

WP Pagination Not Working for Custom Query: Troubleshooting Tips

Ever struggled with WordPress pagination code? Fret not! We’ve got your back. In this post, we...

Woocommerce single product page css broken

If your WooCommerce single product page’s CSS is broken, here are some steps to troubleshoot a...

Recent Posts