This is my current query:
query_posts(array_merge(array('tag' => $pagetag,'meta_key'=>priority,'orderby' =>meta_value, 'order' =>'ASC','paged' => get_query_var('paged'))));
My problem is that the query shows me only the post that has values for my 'meta_key' meaning that 'priority' is not NULL. How can I improve this query so that it will still orderby my meta_key but will show all the posts that aren't NULL as well?
Thanks in advance!
The easiest way to do this is to insert the custom field using
save_post
action, so every post published will have its ownmeta_key
with a default value.Use a MySQL query for add
post_meta
to all posts has not the meta. Thats it.If you/anyone need code help on this, just reply :)
UPDATE
As Timusan asked, add this code in your functions.php file after changing the meta-key name :
The problem is that WordPress adds an
INNER JOIN
to thewp_postmeta
table as soon as you mentionmeta_key
in your conditions. One way around the problem is to add a filter on theorder by
clause, something like this:Note MySQL sorts NULLs first - if you want them sorted last, try something like this (assuming all your priorities come before ZZZZZ alphabetically):
Edit
Here's a bit more explanation, which assumes you understand SQL at least a bit.
Your original
query_posts
resulted in the following query running against the database:That
INNER JOIN wp_postmeta
is what removed any posts without a priority from your results.Removing the
meta_*
related conditions from yourquery_posts
:solved that problem, but the sort order is still wrong. The new SQL is
The
posts_orderby
filter allows us to change theORDER BY
clause:wp_posts.post_date DESC
gets replaced by what the filter returns. The final SQL becomes:which does what you're after.
I needed to perform a similar task on the users.php page for a custom column I added and used the following code that I modified from Hobo
Hopefully this helps somebody in need of this information.
In an effort of being throughout, the remainder of the necessary code to complete my individual task is below.
The Issue: Sorting by a custom field without excluding posts that don't have a value set for that custom field.
Hobo's answer explains this well. Here I'm just going to offer a simpler alternative that ended up being easier in my case (Please note this won't work correctly if pagination is needed).
I decided to do the sorting in PHP after the query is made. The nice part is that I have better control over where the posts with null values end up (I wanted them to show up last).
Here I have a numeric custom field called
sort_ranking
and I'm using it to sort ASC. Posts with a null value for this field are assigned 9999 so that they end up at the end. (Note: I'm using ACF, hence theget_field
function)Hope this helps someone!