WordPress – PHP for Simple Related Links (Using Categories)

WordPress
Want to display posts from the same category as whatever post is being viewed?

No problem. Simply copy the below and paste it into your theme wherever you’d like them to be displayed.

Good spots: bottom of the post, footer, sidebar.

This is set to spit out 5 posts right now. Change as needed.

<?php
global $post;
$cat_ID=array();
$categories = get_the_category();
  foreach($categories as $category) {
    array_push($cat_ID,$category->cat_ID);
  }
  $args = array(
  'orderby' => 'date',
  'order' => 'DESC',
	'post_type' => 'post',
	'numberposts' => 5,
	'post__not_in' => array($post->ID),
	'category__in' => $cat_ID
  ); // post__not_in will exclude the post we are displaying
    $cat_posts = get_posts($args);
if ($cat_posts) {
  foreach ($cat_posts as $cat_post) {
    ?>
<a href="<?php echo get_permalink($cat_post->ID); ?>"><?php echo get_the_title($cat_post->ID); ?></a><br />
    <?php
  }
}
?>

With WordPress, there’s generally a million different ways to accomplish any given task. So if this code doesn’t work out for you, then try an alternate method.

Leave a Reply

Your email address will not be published.