Skip to content

How-to Guides

Technical References

Code Quality and Best Practices /

Using post__not_in

Using post__not_in means that the query cache hitrate will often be a lot lower. It also results in many combinations of arguments creating separate cached objects for a variety of combinations of posts, using up object cache space.

For example, if you are excluding the current post from a widget showing the most recent “other” 5 posts, using post__not_in results in each post page having a unique, uncached query containing the current post’s ID. You can improve performance by ensuring the post query being used is consistent across all the URLs, and just retrieve the most recent 6 posts, so that it’s retrieved from object cache.

In almost all cases, you can gain great speed improvements by requesting more posts and skipping the excluded posts in PHP.

It can also make the query slower if the exclusion list is large.

For example, instead of:

$other_posts_in_tag = get_posts( array(
    'tag_id' =>  $tag_id,
    'posts_per_page' => $limit,
    'post__not_in'  => $array_of_post_ids_to_skip,
    'suppress_filters' => false,
));
 
foreach ( $other_posts_in_tag as $post ){
    //logic goes here;
}

This is recommended:

$other_posts_in_tag = get_posts( array(
    'tag_id' =>  $tag_id,
    'posts_per_page' => $limit + count( $array_of_post_ids_to_skip ),
    'suppress_filters' => false,
));
 
foreach ( $other_posts_in_tag as $post ){
    if ( in_array( $post->ID, $array_of_post_ids_to_skip ) ){
        continue;
    }
    //logic goes here;
}

Last updated: January 20, 2021