I need to keep the payment dates for a post type I created called "Payments." For this, I created a meta key called "expected_payment_date". I save the expected payment dates as timestamp. For example, I keep the date 2020-05-15 as 1589490000.
I want to list all payments that should be made in a given month using Wp_Query. I try the method below for this, but I got no results. Do you know how I can do this?
$month = '2020-05';
$args = array(
'post_type' => array( 'payments' ),
'posts_per_page' => -1,
'post_status' => array( 'publish' ),
'meta_query ' => array(
'key' => 'expected_payment_date',
'value' => $month,
'compare' => 'LIKE'
)
);
Note: I tried other comparisons like = EXIST in the Compare section.
I need to keep the payment dates for a post type I created called "Payments." For this, I created a meta key called "expected_payment_date". I save the expected payment dates as timestamp. For example, I keep the date 2020-05-15 as 1589490000.
I want to list all payments that should be made in a given month using Wp_Query. I try the method below for this, but I got no results. Do you know how I can do this?
$month = '2020-05';
$args = array(
'post_type' => array( 'payments' ),
'posts_per_page' => -1,
'post_status' => array( 'publish' ),
'meta_query ' => array(
'key' => 'expected_payment_date',
'value' => $month,
'compare' => 'LIKE'
)
);
Note: I tried other comparisons like = EXIST in the Compare section.
Share Improve this question asked May 19, 2020 at 7:21 FarukFaruk 2510 bronze badges1 Answer
Reset to default 0I found the solution after a long search. Thank you very much to Misha Rudrastyh who gave me a great idea in my solution. You can check out the great guide that he prepared for meta_query.
Here is the solution:
First, get the first and last day of the month as described here (thanks for Francois Deschenes).
$month = '2020-05';
// First day of the month.
$first_day = strtotime( date('Y-m-01', strtotime($month)) );
// Last day of the month.
$last_day = strtotime( date('Y-m-t', strtotime($month)) );
I use it as a timestamp because I keep the expected payment dates in this way. For more details, I suggest you check Misha's guide.
Once you have the dates correctly fetched, all you have to do is prepare the wp_query arguments.
$args = array(
'post_type' => array( 'payments' ),
'posts_per_page' => -1,
'post_status' => array( 'publish' ),
'meta_query ' => array(
'key' => '_eo_payment_expected_date',
'value' => array( $first_day, $last_day ),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
);
That is all.