[wp-hackers] Get posts by time range

John Blackbourn johnbillion+wp at gmail.com
Mon Aug 13 19:47:10 UTC 2012


On 13 August 2012 20:31, Dino Termini <dino at duechiacchiere.it> wrote:
> Hi all,
>
> I have a question about query_posts. I need to retrieve all the articles having a given custom field associated to them, but limited to a specific time range. Is there any way of achieving this without adding a filter to posts_where?

As Bill points out, there's not a way to do this in core yet. I've
overcome this previously by adding an 'updated' custom field to every
post with a MySQL-formatted date string whenever the post is updated
(or created, depending on the use-case). You can then use that in a
meta_query like this:

$meta_query = array(
	array(
		'key'     => 'my_key',
		'value'   => 'my_value'
	),
	array(
		'key'     => 'updated',
		'value'   => date( 'Y-m-d H:i:s' ),
		'compare' => '>=',
		'type'    => 'DATETIME'
	)
) );

The 'value' argument for the date can of course be something else such
as date(  'Y-m-d H:i:s', strtotime( '-3 days' ).

HTH
John


More information about the wp-hackers mailing list