Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers

<?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
}
?>
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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