2

My posts have a custom field named production_date and formatted YYYYMMDD.

How can I form a meta_query to select only the YYYY part?

$meta_query_args = array(
    array(
        'key'     => 'production_date',
        'value'   => '2004',
        'compare' => '???'
    )
);
6

The handy thing about how ACF stores dates as YYYYMMDD is you can treat them like integers and get a similar level of functionality as if you were using "true" dates.

For example, to get all dates after 1st Jan 2011, use > 20110101. Those before June 1st 2012? < 20120601. And for your case, all dates within 2004? >= 20040101 && <= 20041231.

Translated into a meta query:

$year = '2004';

$meta_query_args = array(
    array(
        'key'     => 'production_date',
        'value'   => array( $year . '0101', $year . '1231' ),
        'compare' => 'BETWEEN',
        'type'    => 'NUMERIC',
    )
);

Check out the codex for a full explanation of all the arguments.

0
-1

You could use PHP's date and strtotime functions to get a year:

$date_value = '20040619'; // from your production_date custom field

$year = date( 'Y', strtotime( $date_value ) );

$meta_query_args = array(
    array(
        'key'     => 'production_date',
        'value'   => $year,
        'compare' => '???'
    )
);
2
  • 1
    The ??? in the question means "what do I put here?". this won't work and does not answer the question of trying to query values stored as a full date by year. – squarecandy Dec 23 '20 at 19:47
  • @squarecandy wow, I wonder if I just forgot to figure that out before posting. Good catch! My answer is trash lol – phatskat Jan 4 at 19:55

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.