在Wordpress中随机发布

rle*_*sko 9 random wordpress

如何在Wordpress中随机发帖?

我想在页面上显示一个按钮,当按下该按钮时,会从博客中随机发布一个帖子.我不希望在页面上显示随机帖子,我只想要一个指向该帖子的链接.我尝试在Google上搜索代码并在此处进行stackoverflow但没有成功.

谢谢...

更新:

这是我的模板代码:

<?php /*Template Name: Random*/ ?>

<?php get_header(); ?>

<nav><?php wp_nav_menu(array('menu' => 'Main Nav Menu')); ?></nav>

<div id="main-content-archive">

<div class="grey-text">Random post</div>

        <?php $query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );?>

        <?php if (have_posts()) : while ( $the_query->have_posts() ) : $the_query->the_post();
        echo '<li>';
        the_title();
        echo '</li>';
        ?>

<?php endwhile; ?>

<?php else : ?>

    <h2>Not Found</h2>

<?php endif; ?> 

</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Run Code Online (Sandbox Code Playgroud)

bin*_*680 9

创建一个页面模板,并使用以下代码获取随机帖子:

//Create WordPress Query with 'orderby' set to 'rand' (Random)
$the_query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );
// output the random post
while ( $the_query->have_posts() ) : $the_query->the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

// Reset Post Data
wp_reset_postdata();
Run Code Online (Sandbox Code Playgroud)

然后在页面中,只需使用:

<a href="the link to the page">see a random post</a>
Run Code Online (Sandbox Code Playgroud)


rle*_*sko 5

我发现这篇帖子给了我想要的结果......

这是从wpbeginner博客文章中复制/粘贴的解决方案.无侵犯版权之意.

只需将以下代码添加到functions.php文件中:

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

使用mydomain.com/random/作为您href为您的按钮,导致随机职位.

谢谢所有为您提供帮助的人...

干杯!