我根据 WordPress 的纪录片创建了这个非常简单的函数,据我所知,这段代码应该可以正常工作
query_posts(array('orderby' => 'rand', 'post__not_in' => $_SESSION['watched'], 'showposts' => 1));
session 的代码并不比这更高级
if(!in_array($post->ID, $_SESSION['watched'])){
array_push($_SESSION['watched'],$post->ID);
}
如果您知道任何其他解决方案或如何修复此特定解决方案 非常感谢所有答案...如果我遗漏了什么,请告诉我,我会添加该信息。
最佳答案
This topic on wordpress.org似乎与您的问题相关 - post__not_in
显然存在一些相当奇怪的问题。
试试这个:
function removeSeenPosts ($where) {
global $wpdb;
if (count($_SESSION['watched']) > 0) {
$where .= ' AND ' . $wpdb->posts . '.ID NOT IN(' . implode (',', $_SESSION['watched']) . ') ';
}
return $where;
}
add_filter('posts_where', 'removeSeenPosts');
query_posts(array('orderby' => 'rand', 'showposts' => 1));
remove_filter('posts_where', 'removeSeenPosts');
如果这没有帮助(我实际上怀疑),则问题显然与 session 中的帖子 ID 存储有关。
我想到了两件事:
$_SESSION
是否可以在除 header 以外的任何内容都已发送后填充?我不记得了……- 将帖子存储在适当的 cookie 中似乎是一个可行的替代方案,并且作为额外的好处,可以使存储在 session 之间持久存在。
作为插件的未经测试的实现:
function setViewedPostCookies() {
if (is_single())
{
global $wp_query;
if (!isset($_COOKIE['watched']))
{
$excluded_posts = array();
}
else
{
$excluded_posts = implode(',', $_COOKIE['watched']);
}
$excluded_posts[] = $wp_query->post->ID;
$excluded_posts = array_unique($excluded_posts);
setcookie('watched', explode(',', $excluded_posts), time() + 3600000, '/');
}
}
add_action( 'get_header', 'setViewedPostCookies' );
关于php - wordpress 显示之前未显示的随机帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7472717/