Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Custom Field Date Filter Help WordPress


Hi Guys,

I have a custom field called expiry_date with a value of let's say 2010-12-11 00:00:00.

What I would like to do is, in my query loop, only return posts with this expiry_date custom field attached to posts and the following condition:

The date in the expiry_date custom field has to be within 24 hours of expiring, if it past the current date, the post is 'expired' and will not show in the loop or if the post is within 25 hours of expiring, it will also not show etc.

I could have used a hack in the code to do this, but I need pagination to work, so I need this done right in the query.

Answers (4)


Ashfame answers:

I am not sure how this can be done. I mean comparing it within query_posts but if you are missing how you can put up a condition, then it can be done like this :

$args = array( 'meta_key'=>'expiry_date', 'meta_compare'=>'>=', 'meta_value'=>5, 'posts_per_page'=>10 ) )

query_posts( $args );

May be that gives you a hint of how you can calculate the value and then check if its in a range. Checking a single condition is easy as you can see but checking a range might be tricky.

Ashfame comments:

Ah yes!
Nick Parson's answer will work well :)


Nick Parsons answers:

This should do the trick:

$almost_expired = $wpdb->get_col("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'expiry_date' AND HOUR(TIMEDIFF(meta_value, '" .date('Y-m-d H:i:s'). "')) BETWEEN 0 AND 24");
query_posts( array( 'post__in' => $almost_expired ) );

You can then run your loop as normal, and it will only display posts that are within 24 hours of expiring.

Keith Donegan comments:

Thanks Nick, unfortunately that also shows "expired" codes too:

<blockquote>Expiry Date 2010-12-10 23:59:59</blockquote>


idt answers:

Try this:

'posts_per_page' => 10,
'meta_key' => 'expiry_date',
'meta_value' => date('Y-m-d h:i:s'),
'meta_compare' => '<='

idt comments:

And this may also help you: [[LINK href=""]][[/LINK]]

idt comments:

Keith Donegan comments:

Wont' work with pagination well, and my solution was almost the same...

<blockquote>I could have used a hack in the code to do this, but I need pagination to work, so I need this done right in the query.</blockquote>

idt comments:

Can you try this filter:

global $wp_query;
$postid = $wp_query->post->ID;
$expiry_date = get_post_meta($postid, 'expiry_date', true);

function filter_where($where = '') {
$where .= " AND post_date <= '" . $expiry_date . "'";
return $where;

add_filter('posts_where', 'filter_where');
// Perform the query, the filter will be applied automatically


Victor Teixeira answers:

Why don't you just use the Content scheduler plugin?

Keith Donegan comments:

Because the data is an external xml feed.