WordPress Function: Get Related posts by tags
• ∞
I was doing some WordPress work last week and wanted to make related posts based on tags, so this little snippet of code came in handy:
Place this inside your loop on your single page, and it will use the post’s tags to find related posts to display:
<?php
$taxs = wp_get_post_tags( $post->ID );
if ( $taxs ) {
$tax_ids = array();
foreach( $taxs as $individual_tax ) $tax_ids[] = $individual_tax->term_id;
$args = array(
'tag__in' => $tax_ids,
'post__not_in' => array( $post->ID ),
'showposts' => 5,
'ignore_sticky_posts' => 1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<h3>Theoretically Related Posts</h3>';
echo '<ul>';
while ( $my_query->have_posts() ) :
$my_query->the_post();
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
echo '</ul>';
}
wp_reset_query();
}
?>
