WordPress.org

Ready to get started?Download WordPress

Forums

Related Posts via Tag outside the loop (2 posts)

  1. Mohammad Kamal
    Member
    Posted 6 months ago #

    I'm trying to show related posts by tags outside the loop on Single Page. The following code works inside loop but I want to show it outside loop on single page.

    <?php
    //for use in the loop, list 5 post titles related to first tag on current post
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
      echo 'Related Posts';
      $first_tag = $tags[0]->term_id;
      $args=array(
        'tag__in' => array($first_tag),
        'post__not_in' => array($post->ID),
        'showposts'=>5,
        'caller_get_posts'=>1
       );
      $my_query = new WP_Query($args);
      if( $my_query->have_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;
      }
    }
    wp_reset_query();
    ?>
  2. Jose Castaneda
    Member
    Posted 6 months ago #

    Try:

    $tags = wp_get_post_tags( get_the_ID() );
    if ( ! empty( $tags ) ) {
      // Create new query of related
      $related = new WP_Query(
      	array(
      		'posts_per_page' => 5,
      		'tag' => $tags[0]->slug,
      		'orderby' => 'rand'
      	) );
    //
      if( $related->have_posts() ) {
      echo 'Related Posts';
        while ($related->have_posts()) : $related->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;
      }
    }
    wp_reset_postdata();

    Tried it on a local setup but may do the trick for ya.

Reply

You must log in to post.

About this Topic