Exclude Current Post from WP_Query

WordPressPosted on

If you want to build a simple, similar post list – in a single page view – when you query the latest or random posts from a post type you can use WP_Query.

The only thing you should watch is the current post which you should exclude from the query. To do this, you must get the current post’s id with the help of the get_the_ID() function and add it as a value to the post__not_in parameter like so:

$args = [
    'post_type'              => ['jobs'],
    'nopaging'               => false,
    'posts_per_page'         => '5',
    'ignore_sticky_posts'    => false,
    'post__not_in'           => [get_the_ID()]
];

$query = new WP_Query($args);

if ($query->have_posts()) : 
    while ($query->have_posts()) : $query->the_post();
        // HTML template
    endwhile;
endif; 

wp_reset_postdata();

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in WordPress category