Published on December 6, 2019

Other CPT entries in the same taxonomy on single CPT pages

Sridhar Katakam

This members-only tutorial provides the steps to output entries of a specified Custom Post Type that belong to the same custom taxonomy as the current entry while excluding the current post on single CPT entries in WordPress.

Use Case

Let’s say there is a support custom post type with an associated support_category custom taxonomy and one of the support categories could be “Installation” (taxonomy term).

When a support post that has been categorized under this category is being viewed you want to show all other (i.e., excluding the current one being viewed) support posts that have also been categorized under “Installation”.

We can write a custom WP_Query for this. Here’s how.

Note: This is for the use case where a given entry has been categorized under a single custom taxonomy.

Step 1

Edit the Oxygen Template that applies to your singular CPT.

Step 2

Add a Code Block.

PHP & HTML:

<?php
	$post_type = 'support'; // this is the name of the custom post type
	$taxonomy = 'support_category'; // this is the name of the taxonomy
	
	$terms = get_the_terms( get_the_ID(), $taxonomy );

	$args = array(
		'post_type' => $post_type,
		'post__not_in' => array( get_the_ID() ),
			'orderby' => 'title',
			'order' => 'ASC',
			'tax_query' => array(
					array(
						'taxonomy' => $taxonomy,
						'field' => 'slug',
						'terms' => $terms[0]->slug
					)
				)
			);

	$query = new WP_Query( $args );

	if ( $query->have_posts() ) :
		echo '<h3 class="other-articles">Other articles in this section</h3><ul class="more-articles">';
		while ( $query->have_posts() ) : $query->the_post();
			printf( '<li><a href="%s">%s</a></li>', get_the_permalink(), get_the_title() );
		endwhile;
		echo '</ul>';
	endif;
?>

Enter your CPT and custom taxonomy names near the beginning of the code.

CSS (optional):

.other-articles {
  color: #484f56;
  font-weight: 400;
  font-size: 18px;
  margin-bottom: 36px;
}

.more-articles li {
  font-size: 14px;
  margin-bottom: 10px;
}

.more-articles li a {
  color: #484f56;
}

References

https://developer.wordpress.org/reference/functions/get_the_terms/

https://gist.github.com/luetkemj/2023628#file-wp-query-ref-php

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right