Random Wordpress posts outside of the main loop wi

2019-06-13 18:55发布

问题:

Well I can't figure this one out...

I have this Wordpress I use as a photo gallery blog.

I have a basic setup using the main default loop for posts.

Like this:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

//the post

<?php endwhile; ?>

<b>Not Found</b>

<?php endif; ?>

In the sidebar and where ever, I want to appear random posts.

I've managed to do that. With this:

<?php query_posts($query_string . 'showposts=1&orderby=rand'); ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

//the post

<?php endwhile; endif; ?>

It looks amazing! In theory.

There are duplicate posts all over the place. And that just looks stupid.

I have read lots of articles but I just can't seem to get it to work :(

Any help would be much appreciated.

回答1:

Try this code for random post.
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>

Or You can get help from this url mention below
http://codex.wordpress.org/Template_Tags/get_posts


回答2:

After a good night of sleep, here's what I have done:

Creating array with post ID:

<?php $already_posted = array(); ?>

The Main loop where at the end I record the post ID to array:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

//the post

<?php $already_posted[]= $post->ID; endwhile; ?>

    <?php else : ?>

    <b>Not Found</b>

<?php endif; ?>

And the random post code using post__not_in to avoid duplicates and again recording post ID:

<?php $args = array( 'numberposts' => 1, 'orderby' => 'rand', 'post__not_in' => $already_posted );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>

//the post

<?php $already_posted[]= $post->ID; endforeach; ?>

Works evertime!

You can do amazing stuff with this :)

Thanks to paislee and Arvind Pal for helping out.



回答3:

Skip would-be duplicates by remembering displayed ID's from the first loop

$displayed = array(); // create an array that we'll use associatively

In your first loop, each time:

$displayed[get_the_ID()] = TRUE; // <-- save all post IDs in here

Change your random loop opening like this:

<?php if (have_posts()) : while (have_posts()) : the_post();
    // skip  post IDs you've already seen
    if ($displayed[get_the_ID()]) continue;
?>

Due to randomness in the number of duplicates, you may want to alter your query so that it gets all posts, and change the second loop to break once the desired number of random posts is reached.

Notes

  • showposts is depracated. Replace showposts=1 with posts_per_page=-1