在Wordpress中获得随机帖子 [英] Get random post in Wordpress

查看:86
本文介绍了在Wordpress中获得随机帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Wordpress中获得随机帖子?

How do I get a random post in Wordpress?

我想在页面上显示一个按钮,当按下该按钮时,它会显示来自博客的随机帖子.我不想在页面上显示随机帖子,我只想要一个指向该帖子的链接. 我尝试在Google以及此处的stackoverflow上搜索代码,但没有成功.

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 to be displayed on the page, I just want a link that leads to that post. I tried searching for a code on Google and here at stackoverflow but no success.

谢谢...

更新:

这是我的模板代码:

<?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(); ?>

推荐答案

我发现

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

这是来自wpbeginner博客文章的解决方案副本/已粘贴.没有侵犯版权的意图.

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

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

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;
   }
}

使用mydomain.com/random/作为href作为您指向随机帖子的按钮.

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

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

Thanks everyone who contributed for your help...

干杯!

这篇关于在Wordpress中获得随机帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆