Lego2012
12/13/2016 - 2:48 PM

Jo Waltham's code for outputting related terms

Jo Waltham's code for outputting related terms

<?php
//* Do NOT include the opening php tag shown above. Copy the code shown below.

// Set up variables
    $filed_under = '';
    $related_content = '';
    $the_post_id = get_the_ID();
    $exclude_ids[] = $the_post_id;
    $count = 0;
    $related_tax = array( 'vendors', 'housing-association', 'topics', 'type');
    
    foreach ( $related_tax as $this_related_tax ) {
        if( $count < 5 ) {
        
            $related_terms = wp_get_post_terms( $the_post_id, $this_related_tax, array("fields" => "ids"));
            
            if ( $related_terms ) {
                $args = array(
                    'posts_per_page' => 5 - $count,
                    'post__not_in' => $exclude_ids,
                    'tax_query' => array(
                                        array(
                                            'taxonomy' => $this_related_tax,
                                            'field' => 'id',
                                            'terms' => $related_terms
                                        )
                                    )
                );
                $related_terms_query = new WP_Query( $args );
                if ($related_terms_query->have_posts() ) {
                    while ($related_terms_query->have_posts()) {
                        $related_terms_query->the_post();
                        $related_items[] = '<a href="' . esc_url( get_permalink() ) .'">' . get_the_title() . '</a>';
                        $exclude_ids[] = $post->ID;
                        $count++;
                    } // end while ($related_terms_query->have_posts())
                }  // end if ($related_terms_query->have_posts() )
            }  // end if ( $related_terms ) 
        } // if( count < 5 ) {    
    } // end foreach ( $related_tax as $this_related_tax )

    
    
    wp_reset_query();    
    
    if( $related_items ) {
        $related_content = '<h2>Related Content</h2><ul><li>' . implode( '</li><li>', $related_items ) . '</li></ul>';
    }

<!-- It echos out the $related_content later. -->

<!-- [7:39] I had to find the related terms of the post first, so you’ll not need that. Also posts could exist in multiple terms and I didn’t want any repeated so I took note of the post IDs of posts already added -->

<!-- [7:39] I’m using a count to make sure I don’t get more than 5 -->