Order by meta field forces ignore of null records
|Reported by:||tomauger||Owned by:|
|Component:||Query||Keywords:||has-patch needs-unit-tests meta-query|
When doing a sort on posts with a meta value, the way the SQL is currently generated in meta.php creates a condition where records that DO NOT have the queried meta value are excluded from the results. This may or may not be the desired behaviour, but we don't give developers the choice without resorting to custom queries or manual rewrites of large swathes of the $clauses array.
The issue: the way WP_Meta_Query->get_sql() creates the join on the meta key is by setting an inner join on wp_postmeta and then adding the key test to the where clause.
I would suggest writing an outer (left) join on wp_postmeta, with the key condition in the join. This would also eliminate any potential future ambiguity if, for example, you are sorting on one meta key but filtering on another, since the key condition would be within the join clause, not the where clause:
LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'my_custom_field_name'
Related to ticket 18158 http://core.trac.wordpress.org/ticket/18158 is the question of how we expose this to the developer in the query API.
'meta_key' => self::get_meta_key( 'my_custom_field_name' ), 'orderby' => 'meta_value', 'exclude_empty_meta' => false
If this gets any traction I would be happy to submit a patch.
Change History (9)
comment:4 wonderboymusic — 8 months ago
- Keywords has-patch added
- Milestone changed from Awaiting Review to 3.7
- Keywords needs-unit-tests added
- Milestone changed from 3.7 to Future Release