admin管理员组文章数量:1325720
I have the settings so only one post (which is by default the most recent) displays with index.php
my current working code
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
How could I change to code to display a random post from any category/date?
It just needs to be one post if that makes a difference.
many thanks
I have the settings so only one post (which is by default the most recent) displays with index.php
my current working code
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
How could I change to code to display a random post from any category/date?
It just needs to be one post if that makes a difference.
many thanks
Share Improve this question asked Aug 24, 2012 at 14:02 bracketboybracketboy 134 bronze badges3 Answers
Reset to default 1Place the following code in your theme functions.php file.
function one_random_post_on_home_page( $query )
{
if ( ! ( $query->is_home() && $query->is_main_query() ) )
return;
$query->set( 'orderby ', 'rand' );
$query->set( 'posts_per_page', 1 );
}
add_action( 'pre_get_posts', 'one_random_post_on_home_page' );
I'm assuming when you say index.php you mean your blogs home page. The index.php file in your theme can be used for many other areas of your website so making any alterations in that file might have undesired effects else where.
Combine the two codes above like this:
function one_random_post_on_home_page( $query )
{
if ( ! ( $query->is_home() && $query->is_main_query() ) )
return;
query_posts(array('orderby' => 'rand', 'showposts' => 1));
}
add_action( 'pre_get_posts', 'one_random_post_on_home_page' );
Try posting this code above your current code:
<?php query_posts(array('orderby' => 'rand', 'showposts' => 1)); ?>
本文标签: display random posts on indexphp instead of latest
版权声明:本文标题:display random posts on index.php instead of latest 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742194325a2430796.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论