Get related posts by custom taxonomy

Posted on: 28 January 2014
random header of a mountain

In this post we're going to use wp_query and custom taxonomies. Let the fun begin!

What we want is to retrieve posts related to the one we are currently displaying through one (or more) custom taxonomy term by using the following snippet to retrieve the current post type and use it in creative ways. In my case, since I was out of creativity, I just chose to run a simpler query whenever the post_type is not "event. Check it out.

post_type = get_post_type();

if ($post_type == 'event'){
  $args = array(
    'post_type' => 'post',
    'posts_per_page' => '3',
    'tax_query' => array(
    'relation' => 'AND',
        'taxonomy' => 'shtags',
        'field' => 'slug',
        'terms' => $myterm,
        'operator' => 'IN'
  $my_posts = new WP_Query($args);
} else {
    $args = array(
    'post_type' => 'post',
    'posts_per_page'  => '1'
  $my_posts = new WP_Query($args);

Credits go mainly to Smashing Magazine and hours of Googling in order to search for an easy solution.