So I actually ran into very strange issue. For some reason some not related posts are fetched using WP_Query object regardless if I pass post__in parameter with a couple of post ids that exist in my database.
Here's the code:
require 'wp-config.php';
$newStuff = new WP_Query(['post__in' => [21757, 9595], 'orderby' => 'post__in']);
echo "<pre>";
var_dump($newStuff);
echo "</pre>";
And as you can see I have already specified the array for 'post__in' key, those records already exist in the database, but when I dump that variable. I see that in fact it returned 6 posts, this is the excerpt of dumped variable:
["posts"]=>
array(6) {
[0]=>
object(WP_Post)#25538 (24) {
["ID"]=>
int(21757)
["post_author"]=>
string(1) "1"
["post_date"]=>
string(19) "2021-04-21 21:54:37"
["post_date_gmt"]=>
string(19) "2021-04-21 18:54:37"
["post_content"]=>
string(12249) "........
It has six posts inside 'posts' key, which doesn't make any sense. I now I can't just modify the WP_Query object which would be a bad practise.
Also the raw query looks like this:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.ID IN (21757,9595) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
I executed it manually in PhpMyAdmin and it returned two rows, which is correct. But I can't seem to understand how it returns 6 posts the way it does, it looks like post__in key is not respected at all.
Any insights or thoughts would be welcome here
CodePudding user response:
Sticky posts will still get selected, when you try to limit the selection to specific post IDs with post_in
.
This is explicitly mentioned in the documentation - and also, what to do against it.
https://developer.wordpress.org/reference/classes/wp_query/#post-page-parameters:
post__in (array) – use post ids. Specify posts to retrieve. ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use
ignore_sticky_posts
.