获取在过去x小时内更新或发布的帖子

时间:2013-02-07 作者:Joshua Richards

好的,我正在尝试获取在过去x时间内发布的帖子,选项有8小时、24小时或72小时。我将变量传递给我的featureHandler。通过ajax访问php,然后返回帖子,下面是我的做法:

$vars = $_GET[\'vars\'];
$time = $vars[0];
$order = $vars[1];

if ($time == 8 ) {
    function filter_where($where = \'\') {

        //posts in the last 8 Hours
        $where .= " AND post_date > \'".date(\'Y-m-d H:i:s\', strtotime(\'-8 hours\'))."\'";
        return $where;
    }
    add_filter(\'posts_where\', \'filter_where\', 10, $time);
} elseif ($time == 24) {
    function filter_where($where = \'\') {

        //posts in the last 24 Hours
        $where .= " AND post_date > \'".date(\'Y-m-d H:i:s\', strtotime(\'-24 hours\'))."\'";
        return $where;
    }
    add_filter(\'posts_where\', \'filter_where\', 10, $time);
} elseif ($time == 72) {
    function filter_where($where = \'\') {

        //posts in the last 72 Hours
        $where .= " AND post_date > \'".date(\'Y-m-d H:i:s\', strtotime(\'-72 hours\'))."\'";
        return $where;
    }
    add_filter(\'posts_where\', \'filter_where\', 10, $time);
}

?>

<div class="article-wrapper">
<?php

query_posts(array(
       \'post__not_in\' => get_option(\'sticky_posts\'), 
));

$itemCount = 0;

while ( have_posts() ) : the_post();
我认为这是半工作状态,除了我刚刚创建的一个帖子,只显示在24或72中,但在$time==8的情况下,这是为什么?我怎样才能使这段代码更有效率?

衷心感谢您。

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

下面是一个假定GET参数的较短版本?time=[integer] (例如?时间=8)

add_filter(\'posts_where\', \'filter_where\', 11);
function filter_where($where = \'\') {
    if(isset($_GET[\'time\'])){
        $time = $_GET[\'time\'];
        $time=(int)$time; // only allow integers
        if(in_array($time,array(8,24,72))){
            $where .= " AND post_date > \'".date(\'Y-m-d H:i:s\', strtotime(\'-".$time." hours\'))."\'";
        }
    }
    return $where;
}

结束