Skip to content

How-to Guides

Technical References

Improve performance by removing usage of post__not_in

Using post__not_in means that the query cache hitrate will often be a lot lower. It can also make the query slower if the exclusion list is large. In almost all cases you can gain great speed improvements by requesting more posts and skipping the posts in PHP.

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;
}

do this:

$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, $array_of_post_ids_to_skip ) ){
        continue;
    }
    //logic goes here;
}

Last updated: November 19, 2020