HomeTips & Tricks How to exclude current post from WP_Query

How to exclude current post from WP_Query

How To Exclude Current Post From WP_Query In WordPress Recent List
How To Exclude Current Post From WP_Query In WordPress Recent List

Do you want to exclude or skip current post from the WP Query? So here is a small WordPress snippet which is that allows you to exclude or skip the current WP post from the WP Query, For example you can try or use on list of recent posts, related post, or more posts from the same category etc. What the snippet does, is getting the ID of the current post and then use this post ID to exclude the current post form being included in the query.

INSTRUCTIONS

Simply copy paste or add the following code in to your WordPress theme template files where you usually use your queries and you can modify code as per your needs i.e. ‘showposts’ => ‘4’, ‘cat’ => ‘1’. etc

<?php
$excludeCurrentID = get_the_ID();
$query = new WP_Query( array(‘showposts’ => ‘4’, ‘cat’ => ‘1’, ‘post__not_in’ => array($excludeCurrentID)));
while ( $query->have_posts() ) : $query->the_post(); ?>
<h2><a href=”#”><?php the_title() ?></a></h2>
<?php the_content(); ?>
<?php endwhile; ?>

I hope this code will help you.

In the end

I hope you have found this article helpful. Let us me your opinion or questions if any through the comment form in below or use this form to ask your question.

You May Also Like

About the Author: Kedar Adhikari

I am WordPress Themes developer and designer and also any type of website design with minimum cost. for more information you can contact me on email [email protected]

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2024 My WP Helper. All rights reserved.