WordPress.org

Forums

Show other posts in same two categories (2 posts)

  1. Pru
    Member
    Posted 5 years ago #

    I found code by MichaelH from ten months ago on this post which almost does exactly what I want. It shows related post titles (excluding the current post) that are in the same category as the current post, or if there are none it does nothing. What I want to do is make it work on two categories so if the other posts are in the same two categories as the current post, show them.

    If it matters, my posts always belong to children of two parent categories.

    Here's his original code:

    <?php
    if ( is_single() ) {
      $cats = wp_get_post_categories($post->ID);
      if ($cats) {
        $first_cat = $cats[0];
        $args=array(
          'cat' => $first_cat,
          'post__not_in' => array($post->ID),
          'showposts'=>5,
          'caller_get_posts'=>1
        );
        $my_query = new WP_Query($args);
        if( $my_query->have_posts() ) {
          echo 'Related Posts';
          while ($my_query->have_posts()) : $my_query->the_post(); ?>
            <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
           <?php
          endwhile;
        } //if ($my_query)
      } //if ($cats)
      wp_reset_query();  // Restore global post data stomped by the_post().
    } //if (is_single())
    ?>

    I haven't been able to find any plugins or other posts on WP that do this. I did find another snippet but it is based on query_posts and I just want to show linked titles:

    <?php query_posts(array('category__and'=>wp_get_post_categories($post->ID))); ?>

    Thanks for any help here. I'm not much of a coder but I have spent a few hours researching this, so I'm not lazy just not talented. ;)

  2. Pru
    Member
    Posted 5 years ago #

    I did find that the Yet Another Related Posts Plugin has a feature for showing related posts that only appear in two or more of the same categories. That's one limited way of accomplishing what I want to do, though I cannot specify which categories.

Topic Closed

This topic has been closed to new replies.

About this Topic