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 am trying to create a query to pull future events only. It was working great until the client requested the ability to add date ranges--so the event will either have a start date only, OR a start date and an end date. I need to build a query that pulls events events that has a start date in the future OR an end date in the future. This does not work as expected and pulls all events; and the order of what's pulled seems random, despite setting orderby to meta_value. Any help would be much appreciated!

    function get_upcoming_events($num) {
    $today =  gmdate('Y-m-d', time()-28800);

    $args = array(
        'meta_key'          => 'event_date',
        'order'             => 'ASC',
        'orderby'           => 'meta_value',
        'post_status'       => 'publish',
        'posts_per_page'    => $num,
        'post_type'         => 'events',
        'meta_query' => array(
            'relation'=>'OR',
            array(
                'key' => 'event_date',
                'type' => 'DATE',
                'value' => $today,
                'compare' => '>=' 
            ),
            array(
                'key' => 'end_date',
                'type' => 'DATE',
                'value' => $today,
                'compare' => '>=' 
            )
        )
    );

    if ( isset( $data[ 'taxonomy' ]) ) {
        $args[ 'tax_query' ] = array();
        $args[ 'tax_query' ][0] = array(
            'field'     => 'slug',
            'taxonomy'  => 'event-type',
            'terms'     => 'general'
        );
    }
    $myquery = new WP_Query( $args );
    return $myquery;
    }
share|improve this question
add comment

1 Answer 1

You're getting all the posts because you set 'meta_key' => 'event_date'.

This is equivalent to adding another subquery into 'meta_query' that says "get me all posts which have an event_date custom field, with any value OR that have even_date to $today etc.".

PS: There are many event plugins out there that have already figured all this stuff out. Give them a try or at least look at their code.

share|improve this answer
    
ahhh that's it. Thanks so much!! –  Kristin Nov 17 '11 at 21:49
    
I just posted a solution here: wordpress.stackexchange.com/a/128038/21163 –  Parham Dec 30 '13 at 17:02
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.