Select random post every day

时间:2015-06-18 作者:RobbertT

我正在寻找一个脚本,选择每天在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; ?>
有什么想法吗?

2 个回复
最合适的回答,由SO网友:birgire 整理而成

请注意posts_orderby 筛选器不可用于get_posts() 哪里suppress_filterstrue 默认情况下。

您可以使用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; ?>

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post