我正在寻找一个脚本,选择每天在Wordpress中随机发布1篇文章。我找到了下面的代码,但每次刷新页面时都会不断收集新帖子:
<?php
function force_random_day_seed($orderby) {
$seed = floor( time() / DAY_IN_SECONDS );
$orderby=str_replace(\'RAND()\', "RAND({$seed})", $orderby);
return $orderby;
}
add_filter(\'posts_orderby\', \'force_random_day_seed\');
$args = array(\'numberposts\' => 1, \'orderby\' => \'rand\', \'post_type\' => \'listing\');
$totd = get_posts($args);
remove_filter(\'posts_orderby\', \'force_random_day_seed\');
foreach( $totd as $post ) : ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; ?>
有什么想法吗?
最合适的回答,由SO网友:birgire 整理而成
请注意posts_orderby
筛选器不可用于get_posts()
哪里suppress_filters
是true
默认情况下。
您可以使用WP_Query
而是:
$args = [
\'posts_per_page\' => 1,
\'orderby\' => \'rand\',
\'post_type\' => \'listing\',
\'ignore_sticky_posts\' => true,
];
add_filter( \'posts_orderby\', \'force_random_day_seed\' );
$q = new WP_Query( $args );
remove_filter( \'posts_orderby\', \'force_random_day_seed\' );
if( $q->have_posts() )
{
while( $q->have_posts() )
{
$q->the_post();
the_title();
}
wp_reset_postdata();
}
else
{
_e( \'Sorry no posts found!\' );
}
也可以跳过
posts_orderby
筛选回调并仅使用
transients 将结果存储24小时。
SO网友:Domain
尝试使用以下代码:-
<?php
function force_random_day_seed($orderby) {
$seed = floor( time() / DAY_IN_SECONDS );
$orderby=str_replace(\'RAND()\', "RAND({$seed})", $orderby);
return $orderby;
}
add_filter(\'posts_orderby\', \'force_random_day_seed\');
$temp_value = get_option(current_time(\'Y-m-d\'));
if($temp_value == \'\' ){
$args = array(\'numberposts\' => 1, \'orderby\' => \'rand\', \'post_type\' => \'listing\');
$totd = get_posts($args);
foreach($totd as $k=>$v){
update_option(current_time(\'Y-m-d\'),$v->ID);
}
}else{
$totd = get_posts($temp_value);
}
remove_filter(\'posts_orderby\', \'force_random_day_seed\');
foreach( $totd as $post ) : ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; ?>