Reputation: 732
I need to extract all posts inside wordpress which has been published between the last 6 months and today.
I'm using WP_Query
to do this,
$today = new \DateTime();
$prev = new \DateTime();
$interval = new \DateInterval('P6M');
$prev->sub( $interval );
$args = [
'post_type' => 'post',
'date_query' => [
[
'before' => $today->format('Y-m-d H:i:s'),
'after' => $prev->format('Y-m-d H:i:s'),
'inclusive' => true
]
]
];
echo '[POST] Today: ' . $today->format('Y-m-d') . "\n";
echo "[POST] Count:" . $wpQuery->post_count . "\n";
echo '[POST] Start date: ' . $prev->format('Y-m-d') . "\n";
Output
Today: 2017-03-09
Count: 7
Start date: 2016-09-09
If I do a select in wordpress database, within the same to dates I get 2086 rows.
SELECT COUNT(ID)
-> FROM wp_posts
-> WHERE DATE(post_date) >= '2016-09-09' AND DATE(post_date) < '2017-03-09'
-> AND post_type = 'post';
SQL output
+-----------+
| count(ID) |
+-----------+
| 2086 |
+-----------+
What am I doing wrong with WP_Query? Why did I get two different results?
Thanks.
Upvotes: 2
Views: 2867
Reputation: 1306
In your sql query you set post date smaller than 2017-03-09 DATE(post_date) < '2017-03-09'
but in WP_Query with 'inclusive' => true
is Less than or equal to 2017-03-09 DATE(post_date) <= '2017-03-09'
.
You can print sql query generated by WP_Query like this:
echo $wpQuery->request;
Try it:
SELECT COUNT(ID) FROM wp_posts WHERE wp_posts.post_date >= '2016-09-09 15:19:39' AND wp_posts.post_date <= '2017-03-09 16:19:39' AND wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish'
Upvotes: 2
Reputation: 2943
SELECT COUNT(ID)
FROM wp_posts
WHERE DATE(post_date) >= '2016-09-09' AND DATE(post_date) < '2017-09-09'
AND post_type = 'post';
Upvotes: 0