简体   繁体   中英

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?

Currently I have the home page set to show only 1 post, but it's only the latest one. 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.

The best way is to modify the global query by hooking on pre_get_posts.

Insert this code into your theme's 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.

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().

    <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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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