WordPress Query Related Posts From Custom Taxonomy


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







WordPress Query Related Posts From Custom Taxonomy

Today we’re going to dive into creating a custom WordPress query to grab related posts from a custom taxonomy. I’ve been using this a lot lately, most recently on a custom real estate site where we created hundreds of custom taxonomy terms for U.S. counties and cities. On a single property listing we wanted to do a related query to grab posts from the same county. Luckily, this is pretty straight forward and simple to accomplish. Let’s jump right in:

First, let’s grab the term IDs for which this post is assigned to:

<?php $assignedlocations = wp_get_post_terms( get_the_ID(), 'counties', array("fields" => "all")); ?>
<?php $locationids = array(); ?>
<?php foreach ( $assignedlocations as $assignedlocation ) { ?>
	<?php $locationids[] = $assignedlocation->term_id; ?>
<?php } ?>

Since I am trying to find listings that are assigned to the same ‘counties’ custom taxonomy as this post, this query finds all the term IDs for each term assigned. It then stores each ID into an array called $locationids for use later in the query.

Next, lets define our query:

$currentpost = get_the_ID(); 
$args = array(
	'posts_per_page' => 3,
	'post_type' => 'listings',
	'post__not_in' => array($currentpost),
	'orderby' => 'rand',
	'tax_query' => array(
		array(
			'taxonomy' => 'counties',
			'field'    => 'term_id',
			'terms'    => $locationids,
		),
	),
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>

Let’s go through this line by line. Line 1, we’re grabbing the post ID of the post we’re running the query on. This is going to come in handy as we want to exclude it from appearing in the query. The posts_per_page sets the amount of results we want to return, in this case three. As previously mentioned, post__not_in allows us to exclude the post we are currently viewing from appearing in the related query. Finally, I want to randomize the results in this case.

The next section is the tax query where we will utilize our term IDs we found in the first step. So let’s define our custom taxonomy as ‘counties’, specify that we’re matching based on term_id, and then specify the $locationids variable we created in the first step.

Now we can use the results any way we see fit. For a complete example, see below:

<?php $assignedlocations = wp_get_post_terms( get_the_ID(), 'counties', array("fields" => "all")); ?>
<?php $locationids = array(); ?>
<?php foreach ( $assignedlocations as $assignedlocation ) { ?>
	<?php $locationids[] = $assignedlocation->term_id; ?>
<?php } ?>
<?php 
$currentpost = get_the_ID(); 
$args = array(
	'posts_per_page' => 3,
	'post_type' => 'listings',
	'post__not_in' => array($currentpost),
	'orderby' => 'rand',
	'tax_query' => array(
		array(
			'taxonomy' => 'counties',
			'field'    => 'term_id',
			'terms'    => $locationids,
		),
	),
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<h1 class="section-title">Related Properties</h1>
<div id="similar-properties">
	<div class="row">
		<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
			<div class="item col-md-4">
				<div class="info">
					<a href="<?php the_permalink(); ?>">
						<h3><?php the_title(); ?></h3>
					</a>
				</div>
			</div>
		<?php endwhile; ?>
	</div>
</div>
<?php endif; wp_reset_query(); ?>

Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!