Skip to content

Instantly share code, notes, and snippets.

@joecue
Created June 12, 2015 15:25
Show Gist options
  • Save joecue/f7b8184f1bda512e742e to your computer and use it in GitHub Desktop.
Save joecue/f7b8184f1bda512e742e to your computer and use it in GitHub Desktop.
WordPress Related Post Code without need of plugin - Grabbed from http://jointswp.com/wordpress-related-posts-without-plugin/
<?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>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment