Skip to content

Instantly share code, notes, and snippets.

@designhash
Created August 16, 2017 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designhash/b141027a4ae611acc1d472ac122297da to your computer and use it in GitHub Desktop.
Save designhash/b141027a4ae611acc1d472ac122297da to your computer and use it in GitHub Desktop.
Get Related Random Post Types from Similar Taxonomy
<!-- begin custom related loop, isa -->
<?php
// get the custom post type's taxonomy terms
$custom_taxterms = wp_get_object_terms( $post->ID, 'your_taxonomy', array('fields' => 'ids') );
// arguments
$args = array(
'post_type' => 'your_custom_post_type',
'post_status' => 'publish',
'posts_per_page' => 3, // you may edit this number
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'your_taxonomy',
'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();
?>
<!-- end custom related loop, isa -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment