0

How to display related the post from same category in single.php. I have tried but it was not working.

1
  • 1
    Please show us what you have tried.
    – fuxia
    Commented Feb 4, 2019 at 13:28

2 Answers 2

0

On your single.php template, you need to load the category term(s), and then run a query to get other posts. In my example, I load posts from a single category. We have Wordpress SEO plugin installed which allows you to select a primary category if you decide to select several.

$related_articles = array();
$categories = get_the_category();

if($categories) {
   $category_id = $categories[0]->term_id;

   if(count($categories) > 1 && class_exists('WPSEO_Primary_Term')) {
      $primary_term = new WPSEO_Primary_Term('category', get_the_id());
      $category_id  = $primary_term->get_primary_term();
   }

   $related_articles = get_posts(array(
      'category'    => $category_id,
      'exclude'     => $post->ID,
      'numberposts' => 3,
      'order'       => 'DESC',
      'orderby'     => 'date',
      'post_status' => 'published',
      'post_type'   => 'post'
   ));
}

You can then loop through the related posts, if any:

<?php if($related_articles): ?>
   <section class="related-articles">
      <?php foreach($related_articles as $post): ?>
         <?php setup_postdata($post); ?>
         <article>
            <h2><?php the_title(); ?></h2>
         </article>
      <?php endforeach; ?>
      <?php wp_reset_postdata(); ?>
   </section>
<?php endif; ?>

Hope that helps

0

To display related posts from the same category in a single post view single.php

// Get the current post ID
$current_post_id = get_the_ID();

// Get the current post categories
$categories = get_the_category($current_post_id);

// Get the first category (you can modify this logic based on your needs)
if (!empty($categories)) {
    $category_id = $categories[0]->term_id;

    // Custom query to get related posts from the same category
    $related_args = array(
        'category__in' => array($category_id),
        'post__not_in' => array($current_post_id),
        'posts_per_page' => 3, // Adjust the number of related posts to display
        'orderby' => 'rand', // Display related posts in random order
    );

    $related_query = new WP_Query($related_args);

    // Output related posts
    if ($related_query->have_posts()) {
        echo '<h3>Related Posts</h3>';
        echo '<ul>';
        while ($related_query->have_posts()) {
            $related_query->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        echo '</ul>';
    }

    // Restore original post data
    wp_reset_postdata();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.