order by custom field include even if empty – wordpress

I have a query for a page of posts.

It return results based on a custom post type, and custom field value. Now I’ve added the ability to order the results based on another custom field.

Read More
$loop = new WP_Query( array ( 'post_type' => 'new', 'orderby' => 'meta_value_num', 'meta_key' => 'over-length', 'meta_query' => array( array( 'key' => 'over-make', 'value' => 'Doral', 'compare' => 'LIKE') ) ) );

I’ve run into a bit of a problem. I’m ordering the results by a custom field called ‘over-length’ but it seems that if a post doesn’t contain a value for ‘over-length’ it is excluded from the results.

I’m wondering how could I change my code so that it included post that don’t have a value for orderby.

Also just thought of a workaround, but not sure how to do it. I’m using a plugin called “more fields” to create my custom fields. Would it be easier to check if the ‘over-length’ field is empty and set it to 0? if so how do I go about doing this.

Update

I’ve looked into the issue a bit further. It seems that if no value is given to ‘over-length’ the custom field is not added to wp_postmeta in the database. If I give a post a over-length value then go back and remove it it does in fact include the result in my query as the field still exist in the database. So how can I get this custom field to be entered into the database if it has a value or not?

Related posts

Leave a Reply

1 comment

  1. About your last request – for a way to add a meta_key (custom field) on all posts even if it is left blank:

    I often use the plugin Custom Fields Template for this kind of thing. It is similar to the one you are using (more fields) but it gives you many possibilities to play with the fields, and most importantly for this case, you can adjust hidden fields and default values. You can perhaps set a default=’ ‘ (space) to have the field inserted if left blank. Or, with a bit more work, modify the plugin code to insert all the fields to DB without checking for empty the values. In the case of CustomFieldsTemplate it shouldn’t be hard to do it.