I previously made a post here: How do I sort by a custom field without manually creating a new page?
However, I believe I asked the wrong question (and I may still be asking the wrong question). Actually think I may need a complex query that will display posts ordered by a meta value. The site is using a theme called “AgentPress”. I believe passing params via the URL bar may be too simplistic for what I need.
Honestly I like the way the current category pages display (formatting, etc.), I simply need to “short-circuit” the process so that any category/archive page is sorted by the meta_key for the “property price” as opposed to the date of entry. If there is a simple, more “WordPress-y” mechanism for doing this, I’m all ears. Please be explicit about where to place the code, etc.
FYI, at this point it’s clear that passing “order=ASC” and “order=DESC” in the URL works. However, it seems that nothing I do with “meta_key” or anything related has any effect.
Thanks in advance.
You can add a filter on
pre_get_posts
hook.Put this code in
functions.php
(in your theme dir) :You can use
meta_value
instead ofmeta_value_num
(available with v2.8), but I assume that price is a numeric value.If you find you lose your navigation menu, I updated @soju’s answer as follows:
Then the filter won’t affect your nav menu
I believe you will find this functionality under a class called PostsOrderedByMetaQuery that extends WP_Query and accepts new arguments ‘orderby_meta_key’ and ‘orderby_order’
You would call it like this:
You can copy the PostsOrderedByMetaQuery class to your theme’s functions.php file, or you can use it within a .php file of a plugin you may be writing.