NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Sep 07 2022
Estimated reading time : 1 minute, 42 seconds - 214 words
With this WordPress tutorial, we will create a query that will allow you to exclude the current ID from your Post Type.
In our example, we already have a Post Type called Services. Let’s say we want to consult one of our services, WordPress will get the data from the single-services.php file and if WordPress doesn’t find this file, it will call single.php.
If you don’t have a single-posttype.php file (Ex:single-services.php), make sure to create it if you want to be able to customize it with HTML and CSS.
Once your file is ready, let’s add our Query Post Type in our sidebar DIV by excluding the current post ID.
Excluding the Current ID With a Query Post Type
<?php $i = 1; $currentID = get_the_ID(); $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query( array( 'post_type' => 'services', 'showposts' => '5', 'post__not_in' => array($currentID) ) ); while ($wp_query->have_posts()) : $wp_query->the_post(); ?> /// Votre loop ici <?php echo $i; ?> <?php $i++; endwhile; ?> <?php $wp_query = null; $wp_query = $temp; // Reset ?>
The first line, $i = 1;, will allow you to increment by 1 and starting from 1. This means we wil count by number the query order of your services. So if your loop, you can display the sorting number this way:
<?php echo $i; ?>
In our second line of our Query Post Type, we will store the current ID in a variable in order to exclude it with post_not_in (‘post__not_in’ => array($currentID)).
This will display the results of your Post Type in the sidebar except the current page.