Skip to content

Instantly share code, notes, and snippets.

@palpalani
Created September 27, 2012 05:50
Show Gist options
  • Save palpalani/3792407 to your computer and use it in GitHub Desktop.
Save palpalani/3792407 to your computer and use it in GitHub Desktop.
WordPress: Releted posts by tags
/*
* List the related posts by current post tags.
*/
function m3_related_posts(){
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'no_found_rows' => 1,
'post_status' => 'publish',
'posts_per_page' => 5
);
$related_posts = new WP_Query($args);
if( $related_posts->have_posts() ) {
while ($related_posts->have_posts()) : $related_posts->the_post();
echo '<div class="post m3-posts">';
if ( has_post_thumbnail() ){
printf('<a href="%s" title="%s" rel="bookmark" class="post-thumbnail alignleft">%s</a>', get_permalink(), the_title_attribute( 'echo=0' ), get_the_title() );
}
printf('<h2><a href="%s">%s</a></h2><p class="byline post-info"><span class="date published time">%s</span></p>', get_permalink(), get_the_title(), get_the_time(get_option('date_format')));
echo '</div><!--end m3-posts -->';
endwhile;
}
}
wp_reset_query();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment