【问题标题】:Random Wordpress posts outside of the main loop without duplicate posts. How?主循环之外的随机 Wordpress 帖子,没有重复的帖子。如何?
【发布时间】:2012-03-08 07:49:51
【问题描述】:

这个我想不通……

我有一个用作照片库博客的 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; ?>

看起来棒极了!理论上。

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

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

任何帮助将不胜感激。

【问题讨论】:

标签: php wordpress loops random


【解决方案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】:

    睡了一夜之后,我做了以下事情:

    使用帖子 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__not_in 的随机邮编以避免重复并再次记录帖子 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; ?>
    

    永远有效!

    你可以用这个做出惊人的事情:)

    感谢 paislee 和 Arvind Pal 的帮助。

    【讨论】:

    • 这对我不起作用。如果我的主循环在 index.htm 上,而随机循环在 sidebar.php 上,会不会有问题。我已经在 sidebar.php 上添加了我的数组,它应该在主循环之前的 index.php 上吗?
    【解决方案3】:

    通过记住第一个循环中显示的 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到达。

    备注

    • showposts 已弃用。将showposts=1 替换为posts_per_page=-1

    【讨论】:

    • 非常感谢!只有一件事,有时它会留下一个随机的帖子空白。也许你提到的那个'break'事情与它有关......你能给我一些指示吗?
    • @Christian147 编辑您的问题以包含$query_string 的值,我会尽力提供帮助
    • @Christian147 很可能是空白帖子是因为continue 检查不是第二个循环中的第一件事。查看我的更新
    • 我认为 $query_string 没有任何价值,我删除了它,一切仍然有效。请不要问我如何或为什么,我今天来这里之前已经上网了:)
    • paislee,不再重复,这是肯定的,但有时仍然是空白帖子。有更多想法吗?
    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多