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 have a page which displays tour dates for an artist. I use a custom field (TheDate) to give each entry a numerical value so that they will show up in the proper order (regardless of when they were actually posted). The custom field uses these values: 20110315 (this would be used for a date on March 15, 2011. I want the page to only return dates for today and onward and not to return any dates which have passed. I think I have the basics down, but I'm clearly not doing something right. Here's what I have, but it doesn't return anything. If I take out the filter it works (but returns all dates, even past ones) so I must be doing something wrong with the filter. Any help, advice or direction would be greatly appreciated. Thanks very much.

$todaysdate = date('Ymd');

function filter_where( $where = '' ) {

$where .= " AND ( ($wpdb->postmeta.meta_key = 'TheDate' AND $wpdb->postmeta.meta_value >= $todaysdate) ) ";

return $where;
}

add_filter( 'posts_where', 'filter_where' );

$args = array(
'cat' => '4',
'posts_per_page' => -1,
'orderby'  => 'meta_value_num',
'meta_key' => 'TheDate',
'order' => 'ASC'
);

$the_query = new WP_Query( $args );
share|improve this question

1 Answer 1

you don't need to use posts_where for this kind of query , you can just use "meta_query"

$today = date("Ymd");   
$args = array(
    'meta_query' => array(
        array(
            'key' => 'TheDate',
            'value' => $today,
            'compare' => '>='
        )
    ),
    'cat' => '4',
    'posts_per_page' => -1,
    'orderby'  => 'meta_value_num',
    'meta_key' => 'TheDate',
    'order' => 'ASC'
);

$the_query = new WP_Query( $args );
share|improve this answer
    
Thank you so much! That's just what I was looking for. I wasn't familiar with the 'meta_query." It works perfectly.Oh, in case someone else tries to use this, I had to add a comma after the second ) at the end of the meta_query to get it to work –  user3958 Mar 16 '11 at 13:28
    
@Steve Wilkison - Glad it worked out for you and u added the missing comma to the code. –  Bainternet Mar 16 '11 at 13:46
    
@Brainternet, how would this work if TheDate was formatted dmY and not Ymd ? In an SQL query I can use ORDER BY STR_TO_DATE(postmeta.meta_value, '%d%m%Y') ASC, but how about in a meta_query ? –  mike23 May 31 '11 at 21:04

Your Answer

 
discard

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