Created
May 10, 2012 05:00
-
-
Save hsquareweb/2651122 to your computer and use it in GitHub Desktop.
WP: Related Posts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- post this code wherever you would like the related posts to be shown but usually inside single.php --> | |
<?php //for use in the loop, list 5 post titles related to first tag on current post | |
$backup = $post; // backup the current object | |
$tags = wp_get_post_tags($post->ID); | |
$tagIDs = array(); | |
if ($tags) { | |
$tagcount = count($tags); | |
for ($i = 0; $i < $tagcount; $i++) { | |
$tagIDs[$i] = $tags[$i]->term_id; | |
} | |
$args=array( | |
'tag__in' => $tagIDs, | |
'post__not_in' => array($post->ID), | |
'showposts'=>5, | |
'caller_get_posts'=>1 | |
); | |
$my_query = new WP_Query($args); | |
if( $my_query->have_posts() ) { | |
while ($my_query->have_posts()) : $my_query->the_post(); ?> | |
<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3> | |
<?php endwhile; | |
} else { ?> | |
<h2>No related posts found!</h2> | |
<?php } | |
} | |
$post = $backup; // copy it back | |
wp_reset_query(); // to use the original query again | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment