1

I'm having some difficulty to find an example of how to create a loop with posts that had been updated in the last 24 hours.

My idea is to have a page of posts or perhaps on the index.php a lists of posts that had been updated in the last day (24 hours from the time the query is done)

Is this possible ? Is there any way to perform that query ?

Thanks in advance

2 Answers 2

1
<?php
$timelimit=1 * 86400; //days * seconds per day
$post_age = date('U') - get_post_time('U');
if ($post_age < $timelimit) {
echo 'this post is within my time limits '; //DO SOMETHING
}
?>
1
  • Where does this go?
    – Pete
    Jun 8, 2016 at 11:07
0

Depending on where you want your posts to show, the solution will vary. If you want to filter your main homepage, this solution will do:

/**
 * Conditionally add a posts_where filter based on the current query
 *
 * @param object $query
 * @return void
 */
function wpse_53599_24h_pre_get_posts( $query ) {
    if ( is_admin() || ! $query->is_main_query() || ! $query->is_home() )
        return;

    add_filter( 'posts_where', 'wpse_53599_filter_last_24h' );
}
add_action( 'pre_get_posts', 'wpse_53599_24h_pre_get_posts' );

/**
 * Add a clause to posts_where to restrict posts to the last 24h
 *
 * @param string $where
 * @return string
 */
function wpse_53599_filter_last_24h( $where = '' ) {
    $where .= " AND post_date >= '" . date( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS ) . "'";
    remove_filter( 'posts_where', 'wpse_53599_filter_last_24h' );
    return $where;
}

Note that we remove the filter because we don't want to limit every posts query run on the site. Only our relevant ones.

If you want to filter a query other than the main home query, just change the conditional within the pre_get_posts function.

If you want to filter a sub-query, it's even simpler, just add the posts_where filter before your instantiation of WP_Query, and remove it immediately after, and skip the pre_get_posts bit.

1
  • Do we change this... DAY_IN_SECONDS?
    – Pete
    Jun 8, 2016 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.