Wordpress在主循环之外的随机帖子,没有重复的帖子.怎样


Random Wordpress posts outside of the main loop without duplicate posts. How?

我想不出这个。。。

我有一个Wordpress,我把它用作照片库博客。

我有一个基本的设置使用主默认循环的帖子。

像这样:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
//the post
<?php endwhile; ?>
<b>Not Found</b>
<?php endif; ?>

在侧边栏和任何时候,我想出现随机的帖子。

我已经做到了。有了这个:

<?php query_posts($query_string . 'showposts=1&orderby=rand'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
//the post
<?php endwhile; endif; ?>

它看起来很神奇!理论上。

到处都是重复的帖子。这看起来很愚蠢。

我读了很多文章,但我似乎无法让它发挥作用:(

任何帮助都将不胜感激。

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

睡了一夜之后,我做了以下工作:

正在创建具有post-ID:的数组

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

主循环,在结束时我将后ID记录到阵列:

<?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代码使用post__not_in来避免重复并再次记录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; ?>

每次都有效!

你可以用这个做一些了不起的事情:)

感谢派斯利和阿尔温德·帕尔的帮助。

通过记住第一个循环中显示的ID来跳过潜在的重复

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

在你的第一个循环中,每次:

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

改变你的随机循环打开方式如下:

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

由于重复次数的随机性,您可能需要更改查询,使其获得所有帖子,并在达到所需的随机帖子数后将第二个循环更改为break

票据

  • CCD_ 2被脱丙烷。将showposts=1替换为posts_per_page=-1