1

I am trying to add a button to take the viewer to a random post. Below's the code I am using:-

    <?php query_posts(array('orderby' => 'rand', 'posts_per_page' => 1));
    if (have_posts()) :
    while (have_posts()) : the_post(); ?>
        <div class="post-lot">
        <a href="<?php the_permalink() ?>">Yes, Robo! Take me there.</a>
        </div>
    <?php endwhile;
    endif; ?>    

But, it keeps showing two links. If I change posts_per_page to 2, it shows 3 links. I tried adding wp_reset_query but the issue still persists.

  • Where is this code running? The context may provide more clues, especially if you can paste the code wrapped around it. :) – WebElaine May 9 '18 at 16:06
  • 1
    Never use query_posts() until you are 100% sure you have to do so. Use get_posts() or WP_Query instead. See the Code Reference. – Max Yudin May 9 '18 at 16:12
  • @WebElaine Its running on the 404 page. – user1928108 May 9 '18 at 16:17
  • @MaxYudin I also tried using WP_Query as seen here - wpexplorer.com/random-posts-wordpress but the result's the same – user1928108 May 9 '18 at 16:22
5

Most probably you have a sticky post there. If you want exact number of posts you need to ignore sticky posts. So your query should look like this:

query_posts( array(
    'orderby' => 'rand',
    'posts_per_page' => 1,
    'ignore_sticky_posts' => 1,
) );

or as suggested, never use query_posts()

$query = new WP_Query( array(
    'orderby' => 'rand',
    'posts_per_page' => 1,
    'ignore_sticky_posts' => 1,
) );
| improve this answer | |
  • Wow, thanks a lot for that, this fixed the issue and as suggested, I will implement WP_Query. – user1928108 May 9 '18 at 16:59

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.