I have a three custom fields
- Meta Key → YOUR_PREFIX_newcar_body_type
- Meta Key → YOUR_PREFIX_newcar_transmission_type
- Meta Key → YOUR_PREFIX_newcar_variant
and I have to sort posts based on these custom fields and print the title of the post…
Any ideas?
Unfortunately, I don’t believe WordPress has the ability to sort by multiple meta key criteria as part of the query: only one. This is likely because for each meta key value selected, another JOIN is involved. You can also see that there are no hooks to modify the ORDER BY clause in SQL in the
WP_Query
class. This can be seen inwp-includes/query.php
line 2322That said, it is certainly possible to do the ordering in PHP.
This is just one way to achieve ordering by meta key values: join the meta key values with ‘-‘ and sort as a string. You can play with the
prefix_sort_by_meta
function to achieve different sorting methods. Please note that the above code will throw PHP Notices if the various meta keys don’t exist for any of the posts, and should be coded more defensively.