Updates, Tips & Tricks

Updates as Released, Plus My Personal Collection Of WordPress Best Practices

Related Posts By Taxonomy

06 April

Here’s a useful function for displaying all of the related posts in a given taxonomy. I’ve used similar functions in the past in building a shortcode to display a list of the same custom post types that share a common taxonomy.

function related_posts_by_taxonomy( $post_id, $taxonomy, $args=array() ) {
    $query = new WP_Query();
    $terms = wp_get_object_terms( $post_id, $taxonomy );
    if ( count( $terms ) ) {
        $post_ids = get_objects_in_term( $terms[0]->term_id, $taxonomy );
        // Remove the current post ID
        if(($key = array_search($post_id, $post_ids)) !== false) {
            unset($post_ids[$key]);
        }
        $post = get_post( $post_id );
        $post_type = get_post_type( $post );

        $args = wp_parse_args( $args, array(
                'post_type' => $post_type,
                'post__in' => $post_ids,
                'taxonomy' => $taxonomy,
                'term' => $terms[0]->slug,
            ) );
        $query = new WP_Query( $args );
    }
    return $query;
}

Copy it into your functions.php and then call it from a template, or a shortcode function, something like this:

    global $post; 
    $tax='my-custom-taxonomy';
    $related_list = '';
    $related =  related_posts_by_taxonomy( $post->ID, $tax );
    while ( $related->have_posts() ): $related->the_post();
        $related_list.='<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
    endwhile;
No comments yet.

Leave a Reply