[wp-hackers] ordering by a custom field

The WordPress Web Warlock wordpress at web-warlocks.net
Wed May 12 18:35:35 UTC 2010

En/na Brian Fidler ha escrit:
> I'm setting up a custom query for a second loop that displays on my page. I
> want to set a custom field titled 'artwork_order' and be able to access that
> field using ORDER BY in my query.
> something like this, however this isn't working.
> ORDER BY wp_postmeta.meta_value['artwork_order'] ASC
> Is there a proper way to do this?
You can do that with $wp_query and get_posts / query_posts setting the 
params orderby to meta_value, and meta_key to "artwork_order" or whatever.
But if you absolutely need to use the $wpdb query directly, what you 
need to do something like:

ORDER BY wp_postmeta.meta_value ASC
WHERE wp_postmeta.meta_key='artwork_order'

With $wpdb->prepare, that'd be

(...) WHERE wp_postmeta.meta_key=%s (...)

And, though you already know that, let me insist again: it's preferable 
to do it with $wp_query and/or other API elements. If it's just for the 
meta order, there's no need for SQL whatsoever.

More information about the wp-hackers mailing list