我只需要从我的 WordPress 首页上的大约 300 个帖子中随机显示 1 个帖子。当我按刷新时,有时同一篇文章会出现两次或在其他刷新后很快出现。我可以实现类似 iTunes 随机播放模式的功能吗?我现在正在使用这段代码:
<?php
$args = array( 'numberposts' => 1, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) :
?>
<?php the_title(); ?>
<?php endforeach; ?>
最佳答案
这只是一个概念证明,但应该能让您走上正轨。重要提示:
- 必须在任何 HTML 输出发生之前设置 cookie
- 我使用 cookie 作为数组,也许它可以是逗号分隔的列表并使用
explode
为post__not_in
创建数组
- 代码使用 PHP 5.3+ 匿名函数,如果运行较低版本则必须更改
- 当没有设置 cookie 时,您必须进行微调,很可能,我们需要做的是在不使用
not_in
过滤器的情况下再次运行get_posts
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
只是一个示例。 全局 $mypost
可以在主题模板中的任何位置使用(在调整bail out
之后)。
如果处理注册用户,我们可以将值存储在user_meta
中,而不是cookie。 .
关于php - 随机选择一个帖子,不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19570119/