Build Your Own WordPress Related Posts

This code will display related posts by finding posts with the same tags as the current post.
If no related posts are found, the “Related Posts” section will not display.


<?php
// Related Posts Function, matches posts by tags - call using joints_related_posts(); )
function joints_related_posts() {
    global $post;
    $tags = wp_get_post_tags( $post->ID );
    if($tags) {
        foreach( $tags as $tag ) {
            $tag_arr .= $tag->slug . ',';
        }
        $args = array(
            'tag' => $tag_arr,
            'numberposts' => 3, /* You can change this to show more */
            'post__not_in' => array($post->ID)
        );
        $related_posts = get_posts( $args );
        if($related_posts) {
        echo '<h4>Related Posts</h4>';
        echo '<ul id="joints-related-posts">';
            foreach ( $related_posts as $post ) : setup_postdata( $post ); ?>
                <li class="related_post">
                    <a class="entry-unrelated" href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
                    <?php get_template_part( 'partials/content', 'byline' ); ?>
                </li>
            <?php endforeach; }
            }
    wp_reset_postdata();
    echo '</ul>';
}
?>

//Additional arguments

//You can use any of the WP Query args with this function

//https://codex.wordpress.org/Class_Reference/WP_Query

$args = array(
'post_type' => 'YOUR POST TYPE NAME HERE' //this is the line you need to add
'tag' => $tag_arr,
'numberposts' => 3, /* You can change this to show more */
'post__not_in' => array($post->ID)
)

Credit goes to JOINTSWP for posting an actual solution that worked: JOINTSWP

Tweet It. Share It.

See more Code Snippet, php, Wordpress