• Resolved seanjacob

    (@seanjacob)


    Related = Identical tags

    So I am able to display two related posts in a post. But if I can’t find any related posts I want to display any other posts in the category.

    $the_cat = get_the_category();
     $cat_id = $the_cat[0]->cat_ID;
     $the_query = new WP_Query(array('category__in' => $cat_id, 'post__not_in' => array($id), 'orderby' => 'rand', 'posts_per_page' => 2, 'tag' => 'Omega,Seamaster'));
    if( have_posts() ) : while ($the_query->have_posts()) : $the_query->the_post();

    The long way I can do this is count to see how many related posts I retrieve and then run another query if I need to.

Viewing 1 replies (of 1 total)
  • Thread Starter seanjacob

    (@seanjacob)

    I ended up doing it the long way, let me if you find better.

    <?php
          $the_cat = get_the_category();
          $cat_id = $the_cat[0]->cat_ID;
          $c = 0;
          $the_query = new WP_Query(array('post__not_in' => array($id), 'orderby' => 'rand', 'posts_per_page' => 2, 'tag' => 'Omega,Seamaster'));
          if( have_posts() ) : while ($the_query->have_posts()) : $the_query->the_post();
        ?>
          <div class="featured-article">
            <img src="<?php echo wp_get_attachment_url(get_post_meta($post->ID, 'banner', true)); ?>" />
            <h3 class="featured-article-title"><?php the_title() ?></h3>
            <h4 class="featured-article-details"><?php if(get_the_author_id() != 5) { ?>written by <?php the_author(); ?> - <?php } else { ?>Posted <?php } ?><?php the_time('jS M Y'); ?></h4>
            <?php echo get_excerpt(50); ?>
            <?php $c++ ?>
            <?php $last_post = $post->ID; ?>
          </div>
        <?php endwhile; wp_reset_postdata(); endif; ?>
    
        <?php
          $i = 2-$c;
          if ($i > 0){ $the_query = new WP_Query(array('category__in' => $cat_id, 'post__not_in' => array($id, $last_post), 'orderby' => 'rand', 'posts_per_page' => $i));
          if( have_posts() ) : while ($the_query->have_posts()) : $the_query->the_post();
        ?>
          <div class="featured-article">
            <img src="<?php echo wp_get_attachment_url(get_post_meta($post->ID, 'banner', true)); ?>" />
            <h3 class="featured-article-title"><?php the_title() ?></h3>
            <h4 class="featured-article-details"><?php if(get_the_author_id() != 5) { ?>written by <?php the_author(); ?> - <?php } else { ?>Posted <?php } ?><?php the_time('jS M Y'); ?></h4>
            <?php echo get_excerpt(50); ?>
          </div>
        <?php endwhile; wp_reset_postdata(); endif; ?>
        <?php } ?>
Viewing 1 replies (of 1 total)
  • The topic ‘How to display non related posts after related posts?’ is closed to new replies.