Home > other >  Wordpress meta_query of certain days after date stored in custom field
Wordpress meta_query of certain days after date stored in custom field

Time:04-11

I like to set meta_query for 10 days after date stored in custom field.

I set like this, but it does not work.

Meta key '2a' has value like '2022-02-15'.

<?php
$today = wp_date('Y-m-d');


$args = array(
'meta_query' => array(
                      'relation' => 'AND',


array(
    'key'=> '2a',
    'value' => array( date("Y-m-d", strtotime(" 10 day", strtotime(get_post_meta($post->ID , '2a' ,true)))),  $today ),
    'compare' => '<=',
    'type' => 'DATE',
    ),

array(
    'key'=> '3a',
    'compare' => 'EXISTS'
    ),


                                                                                             
));?>

CodePudding user response:

You're passing two values into the date portion of your query which suggests you need to compare between as opposed to <=.

I tend to find it's better to perform calculations first and then pass the result into the query. Merging it all together as in your example makes it much harder to follow.

While strtotime() will work, there are classes that make handling time easier and more readable.

Example:

// Keeping the code brief for the example but you'll probably want to do some checks here.
$twoADate = new DateTimeImmutable( get_post_meta( $post->ID , '2a' ,true ) );

$tenDaysLater = $twoADate->modify( ' 10 days' )->format( 'Y-m-d' );
$today = wp_date( 'Y-m-d' );

$args = [
    'meta_query' => [
        'relation' => 'AND',
        [
            'key'=> '2a',
            'value' => [$tenDaysLater, $today],
            'compare' => 'BETWEEN',
            'type' => 'DATE', 
        ],
        [
            'key' => '3a',
            'compare' => 'EXISTS'
        ],
    ],
];

CodePudding user response:

$today = wp_date('Y-m-d');
$TenDaysBefore = date("Y-m-d", strtotime("-10 day", strtotime($today)));

'key'=> '2a',
'value' => $TenDaysBefore ,
'compare' => '<=',
'type' => 'DATE',

Works now

  • Related