madeinthearcade
6/23/2017 - 10:23 AM

Display related custom posts from the same taxonomy - ONLY ON SINGLE PAGE

Display related custom posts from the same taxonomy - ONLY ON SINGLE PAGE

	<?php 
	 
	$custom_taxterms = wp_get_object_terms( $post->ID, 'product-categories', array('fields' => 'ids') );
	// arguments
	$args = array(
	'post_type' => 'products',
	'post_status' => 'publish',
	'posts_per_page' => 3, // you may edit this number
	'orderby' => 'rand',
	'tax_query' => array(
	    array(
	        'taxonomy' => 'product-categories',
	        'field' => 'id',
	        'terms' => $custom_taxterms
	    )
	),
	'post__not_in' => array ($post->ID),
	);
	$related_items = new WP_Query( $args );
	// loop over query
	if ($related_items->have_posts()) :
	echo '<ul>';
	while ( $related_items->have_posts() ) : $related_items->the_post();
	?>
	    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
	<?php
	endwhile;
	echo '</ul>';
	endif;
	// Reset Post Data
	wp_reset_postdata();
	?>