user3514052
user3514052

Reputation: 429

how to get related posts list in home page

how can i get list of latest posts with their relative posts by tags?

example:

Upvotes: 0

Views: 81

Answers (2)

Vishal Sharma
Vishal Sharma

Reputation: 1372

use this in Index.php

 <?php 
 $args = array(
'numberposts' => 100,
'offset' => 0,
'category' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'include' => ,
'exclude' => ,
'meta_key' => ,
'meta_value' =>,
'post_type' => 'post',
'post_status' => 'draft, publish, future, pending, private',
'suppress_filters' => true );

 $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
 ?>
<ul>
   <?php

foreach( $recent_posts as $recent )
    {
       echo '<li>'.$recent["post_title"];

         $tags = wp_get_post_tags($recent["ID"]);
          if ($tags)
          {
           $first_tag = $tags[0]->term_id;
           $args=array(
            'tag__in' => array($first_tag),
            'post__not_in' => array($recent["ID"]),
            'posts_per_page'=>100,
            'caller_get_posts'=>1
           );
           $my_query = new WP_Query($args);
           if( $my_query->have_posts() )
           {
           echo '<ul>';
           while ($my_query->have_posts()) : $my_query->the_post(); ?>
          <li><?php the_title(); ?></li>

           <?php
           endwhile;
          echo '</ul>';
           }
             wp_reset_query();
           }

      echo '</li>';
    }
   ?>
</ul>

Upvotes: 1

Bhavesh
Bhavesh

Reputation: 365

you can do something like this your main loop contain recent post so during each loop use following function to get it's tag

 $tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );

then you can use another loop of using those tags

$query = new WP_Query( 'tag_id='.$tag_ids );

now $query has content you want.

Upvotes: 0

Related Questions