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:

1
2
3
4
5
6
7
8
9
$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:

1
2
3
4
5
6
7
8
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:

1
2
3
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:

1
2
3
4
5
6
7
$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 Retrieve and Expose Gutenberg & Theme-Generated CSS in WordPress

If you want to extract the CSS generated by Gutenberg and your WordPress theme, you can do so using ...

Limit total quantity globally for specific product category in WooCommerce

To limit the total quantity globally for a specific product category in WooCommerce, you can use a c...

WordPress Redirect Issues Across Multiple Websites

Experiencing redirect loops or unwanted redirects on multiple WordPress sites? Here’s a guide to d...

Google Tag Manager is Breaking My Oxygen-Built Website (WordPress)

Fix: Google Tag Manager Breaking Oxygen-Built WordPress Website If Google Tag Manager (GTM) is causi...