Get random post in Wordpress

后端 未结 5 1195
你的背包
你的背包 2021-02-19 12:00

How do I get a random post in Wordpress?

I would like to display a button on a page that, when pressed, goes to a random post from the blog. I don\'t want a random post

5条回答
  •  清歌不尽
    2021-02-19 12:47

    I find it is more useful to have a URL that will redirect to a random post that you can use as link in sidebar or in menus. If it is a single WP site and even on wp.com it's really easy, for a blog at

    http://mygroovywpsite.me/
    

    All you need to do is append it with ?random

    http://mygroovywpsite.me/?random
    

    I found this did not work (nor the wp_beginner code above) on subsites in my multisite installation, either approach just loaded the home page. Maybe I had some funky cache issues. The way I do this on many sites is a few more steps w/o plugins.

    First make a Page in your site called "Random" / with the slug "random" -- it does not need any content in it

    Then create a page-random.php template

     'post',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'orderby' => 'rand'
    );
    
    // It's time! Go someplace random
    $my_random_post = new WP_Query ( $args );
    
    while ( $my_random_post->have_posts () ) {
      $my_random_post->the_post ();
    
      // redirect to the random post
      wp_redirect ( get_permalink () );
      exit;
    }
    ?>
    

    Then you get the re-direct for any link on your blog ...../random w/o any wrestling with .htaccess

    I've done it this way because I've had to modify the query, sometimes for custom post type, sometimes to restrict to category, etc.

    I only had one site that was a problem because the hosting suppressed the use of mySQL queries with ORDER BY RAND()

提交回复
热议问题