Skip to content

Instantly share code, notes, and snippets.

@vilmosioo
Created December 5, 2012 18:20
Show Gist options
  • Save vilmosioo/4218120 to your computer and use it in GitHub Desktop.
Save vilmosioo/4218120 to your computer and use it in GitHub Desktop.
How to get related posts in WordPress
<?php
// get current post categories and tags
$categories = get_the_category($post->ID);
$tags = get_the_tags($post->ID);
if ($categories || $tags) {
$category_ids = array();
if($categories)
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$tag_ids = array();
if($tags)
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category_ids
),
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => $tag_ids
)
),
'post__not_in' => array($post->ID),
'posts_per_page'=> 4, // Number of related posts that will be shown.
);
// query posts
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) {
echo "<h3>Related posts</h3><ul>";
while( $my_query->have_posts() ) { $my_query->the_post();
// display each post
?>
<li><a href='<?php the_permalink(); ?>' rel='canonical'><?php the_title();?></a></li>
<?php
}
echo "</ul>";
}
}
wp_reset_postdata();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment