Aa you know, as of WP3.0 there are options for custom advanced queries, which is great.
As of this, some query parameters of custom fields like meta_key, meta_value were deprecated for the new meta_query parameter (see here)
I try to have a pretty simple query with the new syntax, query posts by a certain post_type (services) that contains a specified meta_key (order_in_archive)- this is going well as expected.
But – I want to orderby the query by the meta_value, and with no success.
This is my query –
query_posts(
array( 'post_type' => 'services',
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_query' => array(
array('key' => 'order_in_archive'))
)
);
I tried orderby also by meta_value_numeric and meta_value, but in any case the results are being ordered by the publication date (as regular posts do).
Anyone know how can this be done?
Thanks
You can define the meta key for orderby parameter using the old method (I tested on WP 3.1.1)…
This issue in general is cleared up as of WordPress 4.2 by using named queries. e.g.
For me, I wanted to order by a numeric field and I had to use
'type' => 'NUMERIC'
inside the meta query.The WP Codex is actually confusing when addressing this problem.
You do not actually need the meta_query param to use the orderby, instead it uses the meta_key param, which although by WP Codex is deprecated is has been established here: How do you use orderby with meta_query in WordPress 3.1? that orderyby still needs the meta_key.
so it should be
It´s easy:
Here is my code:
The main detail is: include
meta_key
, my code didn´t order unlessmeta_key
is included, and that’s all:Here is the full code of a list of
directors
pictures order bydirector_weight
:Don’t use query_posts.
Use the WP_Meta_Query parameters
Following solution works:
You needed to provide the key of the meta_query sub array
order_clause
for yourorderby
value.I found this to work quite well.
I had a set of custom event dates I needed to sort by date descending. Since my custom event date was stored in my wp_postmeta table, and was typically different to the post_date or modified dates, this worked for me:
You can then loop through $posts like so: