Get Posts updated or published within the last x hours

Okay, I’m trying to get posts that have been published within the last x amount of time, options being 8, 24 or 72 hours. I have the variables being passed to my featureHandler.php via ajax, then returning the posts, here is how I’m doing it:

$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();

This is semi working, I think, except that a post I just created, only shows up in 24 or 72, but not in the case that $time==8, why is that? And how can I make this code more efficient?

Read More

Thank you SINCERELY.

Related posts

Leave a Reply

1 comment

  1. here is a shorter version that assumes the GET parameter ?time=[integer] (for example ?time=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;
    }