Created
December 4, 2013 19:00
-
-
Save dcooney/7793397 to your computer and use it in GitHub Desktop.
Get related posts by tag in WordPress
This file contains 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
<?php | |
//for use in the loop, list 5 post titles related to first tag on current post | |
$tags = wp_get_post_tags($post->ID); | |
$tag_in = array(); | |
foreach($tags as $tag): | |
setup_postdata($tag); | |
$tag_in[] = $tag->slug; | |
endforeach; | |
$the_tags = implode(",", $tag_in); //Create | |
if ($tags) { ?> | |
<?php | |
//$first_tag = $tags[0]->term_id; | |
//tag_slug__and | |
$args=array( | |
'tag' => $the_tags, | |
'post__not_in' => array($post->ID), | |
'posts_per_page'=>5, | |
'caller_get_posts'=>1, | |
'post_status' => 'publish', | |
'orderby' => 'rand', | |
'order' => 'DESC', | |
); | |
$my_query = new WP_Query($args); | |
if( $my_query->have_posts() ) {?> | |
<section> | |
<h3>Related Posts</h3> | |
<div> | |
<ul> | |
<?php | |
while ($my_query->have_posts()) : $my_query->the_post(); ?> | |
<li><h4><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4><p><?php the_time('F j, Y'); ?></p></li> | |
<?php | |
endwhile; | |
} | |
echo '</ul></div></section>'; | |
} | |
wp_reset_query(); ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment