Get random post in Wordpress

后端 未结 5 1223
你的背包
你的背包 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:36

    I found this post which gave me desired results...

    Here's a solution copy/pasted from the wpbeginner blog post. No copyright infringement intended.

    Just add the following code to the functions.php file:

    add_action('init','random_add_rewrite');
    function random_add_rewrite() {
       global $wp;
       $wp->add_query_var('random');
       add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
    }
    
    add_action('template_redirect','random_template');
    function random_template() {
       if (get_query_var('random') == 1) {
               $posts = get_posts('post_type=post&orderby=rand&numberposts=1');
               foreach($posts as $post) {
                       $link = get_permalink($post);
               }
               wp_redirect($link,307);
               exit;
       }
    }
    

    Use mydomain.com/random/ as your href for your button that leads to the random post.

    Thanks everyone who contributed for your help...

    Cheers!

提交回复
热议问题