简体   繁体   English

WordPress —如何使随机帖子出现在主页上?

[英]Wordpress — how to make a random post appear on home page?

Is there any way to have a different post appear each time someone refreshes the home page of my self-hosted Wordpress blog? 每当有人刷新我自托管的Wordpress博客的主页时,是否有任何方法可以显示不同的帖子?

Currently I have the home page set to show only 1 post, but it's only the latest one. 目前,我的主页设置为仅显示1条帖子,但这只是最新的帖子。 I would like it to be different each time someone visits my site, to pull a post randomly from the archive of all posts. 我希望每次有人访问我的网站时都会有所不同,以便从所有帖子的存档中随机提取一个帖子。

Here's what the loop currently looks like in the theme I'm using: 这是我正在使用的主题中当前循环的外观:

<?php
}

// Load main loop
if ( have_posts() ) {

// Start of the Loop
while ( have_posts() ) {
the_post();
?>

Is there any way to achieve this? 有什么办法可以做到这一点?

I also don't want to keep the "Blog pages show at most 1 post" setting since that messes up my search results (every result is on a separate page) but I only want 1 post to show up on the homepage loop. 我也不想保留“博客页面最多显示1条帖子”设置,因为这会使我的搜索结果混乱(每个结果都在单独的页面上),但是我只希望1条帖子显示在首页循环中。

The best way is to modify the global query by hooking on pre_get_posts. 最好的方法是通过挂钩pre_get_posts来修改全局查询。

Insert this code into your theme's functions.php: 将此代码插入主题的functions.php中:

add_action('pre_get_posts', 'my_pre_get_posts');
function my_pre_get_posts($query) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set('orderby', 'rand');
    }
}

This will check if you're on home page, and if it is the main query (so only the main posts query is targeted), and if that is true, will set the orderby to rand , so each time a random post will appear on the home page. 这将检查您是否在主页上,以及它是否是主要查询(因此仅针对主要帖子查询),并且如果为true,则将orderby设置为rand ,因此每次出现随机帖子时在主页上。

Please, note that if you have pagination on your home page, this will always order your posts in random order, so in this case you might want to build a custom query over your loop, by using the WP_Query class or query_posts(). 请注意,如果您在首页上有分页,这将始终以随机顺序对帖子进行排序,因此在这种情况下,您可能希望通过使用WP_Query类或query_posts()在循环中构建自定义查询。

    <li><h2>Random Post</h2>
<ul>
<?php $posts = get_posts('orderby=rand&numberposts=5'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<?php } ?>
</ul>
</li>

Refer http://codex.wordpress.org/Template_Tags/get_posts 请参阅http://codex.wordpress.org/Template_Tags/get_posts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM