I am tryping to fetch random posts list in single.php above footer. Titles of the post displaying randomly and are unique in <li> but the excerpt is same for every post title (i.e., same excerpt of post content 'single.php').

First tried this:

  <ul class="random-list">
    <?php $posts = get_posts('orderby=rand&numberposts=12'); foreach($posts as $post) { ?>
    <li  class="col-xs-6 col-sm-3"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?><br></a>
    <?php } ?>

Second try:

$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><p><?php the_excerpt(); ?></p></li>
<?php endforeach; ?>

You are trying to use the_title() and the_excerpt() functions outside the wordpress loop, therefore, they will not work.

I suggest you try something like :

$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$query = new WP_Query($args);
    // the_excerpt() will now work as expected
  • Worked but number of posts showing only 5 even after changing into numberposts => 12
    – dan
    Sep 27 '16 at 14:51
  • I fixed it, use posts_per_page in a WP_Query
    – Sladix
    Sep 27 '16 at 17:16

Your get_posts() function may be causing the error that you interpret now.

You can follow up the standard loop structure so that it will be very easy for you to print the title(), content and the excerpt conditions.

$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
   $random_posts = new WP_Query($args);
   if($random_posts->have_posts()) : 
      while($random_posts->have_posts()) : 
         <h1><?php the_title() ?></h1>
         <div class='post-content'><?php the_content() ?></div>
         <div class='excerpt'><?php the_excerpt(); ?></div>      
   Oops, there are no posts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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