1

I have a custom field that has a date picker. This date is in the format 11/12/2019. In my query I have the following:

$meta_query = array(
        array(
                    'key'       => 'date-available',
                    'value'     => date("m/d/Y"),
                    'compare'   => '<',
                ),

    );

This works in that it shows the posts where the custom date is less than the current date for this year and the December dates for this year don't show. But, for some reason the posts that have a date for 01/07/2020 still show. Anyone have an idea as to why?

  • it looks like comparisons like < or > don't work with your date format. in my past developments, I decided to store date as timestamp because I want to control what append. I don't know if it's a waste of resources but it give the expected results. – Kaperto Nov 13 '19 at 1:22
  • All meta are text/string data, so you can't actually use this kind of comparison on a meta that is a date stored as m/d/Y. If you need to do date comparisons, then the meta needs to be stored as epoch time. – butlerblog Nov 13 '19 at 2:01
  • date format should be compared by using db format date('Y-m-d') – Gopala krishnan Nov 13 '19 at 5:01
0

According to the relevant article on the WordPress Codex, you should be able to add a type argument to the meta array. Resulting in something like this:

$meta_query = array(
    array(
        'key'       => 'date-available',
        'value'     => date("m/d/Y"),
        'compare'   => '<',
        'type'      => 'DATE'
    ),
);

It's worth noting, though (as Gopalakrishnan18 mentioned), MySQL expects a date format of Y-m-d; so you may need to update the format of the date in the database.

|improve this answer|||||
  • 1
    I updated the format in the database to the Y-m-d and it worked! Thank for the suggestion! – Tyler Robinson Nov 13 '19 at 7:51

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.