0

I have a query set up to compare the start and end dates for some custom fields. The start date is required for the post; however, the end date is not. This causes some issues with the following:

query_posts(
    array (
        'meta_query' =>
            array(
                array(
                    'key' => 'start_date',
                    'value' => $date,
                    'compare' => '>=',
                    'type' => 'DATE',
                ),
                array(
                    'key' => 'end_date',
                    'value' => $enddate,
                    'compare' => '<=',
                    'type' => 'DATE',
                ),
            )
    )
);

This query works fine when the end date has been set on the post; however, when it hasn't, the post will not get queried at all. Is there a way to check first if the field exists first before doing the <= DATE compare?

  • 2
    I think the most efficient way to do this would be to wrap your own SQL into a $wpdb object. You should avoid use of query_posts regardless, but even using WP_Query, I don't think you can mix conditions (OR, AND) for meta_query. – vancoder Apr 1 '13 at 19:39
0

I know how to do that in pure SQL but I can't get WP_Query to nest conditions in the way required.

If it is acceptable, the easiest way to make this work would be to assign an arbitrary far future end date when the data is saved to the database. Something like strtotime("2038-01-01").

That is a bit of a hack but Core functions should work and you wouldn't need to write your own SQL. Using a fixed date like that means that you can easily find and alter the expiration date if 2038 comes around and you find you need to, or you could remove the date if WP_Query gets patched to handle the kind of query logic you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.