我需要在我的Wordpress首页上显示来自约300个帖子的1个随机帖子。当我按下刷新时,有时相同的帖子会在其他刷新后出现两次或很快。我可以实现iTunes shuffle模式吗?我现在正在使用此代码:
<?php
$args = array( 'numberposts' => 1, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) :
?>
<?php the_title(); ?>
<?php endforeach; ?>
答案 0 :(得分:3)
这只是一个概念证明,但应该让你走在正确的轨道上。重要说明:
explode
为post__not_in
get_posts
过滤器的情况下再次运行not_in
add_action( 'template_redirect', function()
{
# Not the front page, bail out
if( !is_front_page() || !is_home() )
return;
# Used in the_content
global $mypost;
# Set initial array and check cookie
$not_in = array();
if( isset( $_COOKIE['shuffle_posts'] ) )
$not_in = array_keys( $_COOKIE['shuffle_posts'] );
# Get posts
$args = array( 'numberposts' => 1, 'orderby' => 'rand', 'post__not_in' => $not_in );
$rand_posts = get_posts( $args );
# All posts shown, reset cookie
if( !$rand_posts )
{
setcookie( 'shuffle_posts', '', time()-86400 );
foreach($_COOKIE['shuffle_posts'] as $key => $value)
{
setcookie( 'shuffle_posts['.$key.']', '', time()-86400 );
$id = 0;
}
}
# Increment cookie
else
{
setcookie( 'shuffle_posts['.$rand_posts[0]->ID.']', 'viewed', time()+86400 );
$id = $rand_posts[0]->ID;
}
# Set the global, use at will (adjusting the 'bail out' above)
$mypost = $id;
return;
## DEBUG ONLY
# Debug Results - remove the return above
echo 'current ID:' . $id . "<br />";
if( !isset( $_COOKIE['shuffle_posts'] ) )
echo 'no cookie set';
else
var_dump($_COOKIE['shuffle_posts']);
die();
});
add_filter( 'the_content', function( $content )
{
global $mypost;
if( isset( $mypost ) )
$content = '<h1>Random: ' . $mypost . '</h1>' . $content;
return $content;
});
过滤器the_content
只是一个例子。 global $mypost
可以在主题模板中的任何位置使用(在调整bail out
之后)。
如果与注册用户打交道,我们可以将值存储在user_meta
。