在主循环之外的随机Wordpress帖子,没有重复的帖子.如何?

问题描述:

好吧,我想不通...

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

我有这个Wordpress,可以用作相册博客.

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

我使用帖子的主要默认循环进行了基本设置.

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

赞:

<?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.

我已经做到了.与此:

<?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 :(

任何帮助将不胜感激.

经过一整夜的睡眠,这是我所做的:

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

使用帖子ID创建数组:

Creating array with post ID:

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

主循环,最后我将帖子ID记录到数组中:

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; ?>

然后使用post__not_in的随机邮政编码来避免重复,并再次记录帖子ID:

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; ?>

随时都能工作!

您可以用它来做奇妙的事情:)

You can do amazing stuff with this :)

感谢paislee和Arvind Pal的帮助.

Thanks to paislee and Arvind Pal for helping out.