I think, therefore I am. I am, therefore I sail

WordPress: Retrieve posts for last N minutes or timespan

I am working on a project that requires me to pull the last 15 minutes worth of posts from a custom post type out of the wp_posts table for analysis. I thought this would be easy and quick, however I spend around 20 minutes digging until I finally found a nugget way at the bottom of the WP_Query codex page. Web searches and looking through the post functions unfortunately got me nowhere. I hope that if you are looking to do the same thing this post will be a helpful time saver to you.

The following will return posts just from the last 15 minutes

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts in the last 15 minutes
	$where .= " AND post_date > '" . date('Y-m-d', strtotime('-15 minutes')) . "'";
	return $where;
}

add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );

The following will return posts from a timespan of 30 to 60 days old

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts  30 to 60 days old
	$where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'";
	return $where;
}

add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );

Remember, it is good etiquette to prefix the name of your functions with the name of your theme or plugin. So if your plugin is named "Cat Namez" instead of using the filter_where function name you could use catNamez_filter_where. It is a bit longer, however it prevents namespace collisions with other plugins and possible fatal errors or stack overflows.

Be sure to read the WP_Query page on the WordPress Codex too! It is where I stole this code from 🙂

Previous

ZDD: Zippey the Gardener

Next

Useful sites for WordPress developers

1 Comment

  1. shawn

    Thanks for the post. I was just looking into this last night in order to display my bbPress most recent topics. (topic is post-type)

Powered by WordPress & Beards