How to do a wp_query using “BETWEEN” with two meta_values?

I’m starting with WordPress, already achieved some queries, but this one… ugh! It’s being a pain to me!

What i want to do is this part of query:

Read More
" ... WHERE "VALUE_THAT_I_WANT" BETWEEN event_start_date AND event_end_date ..."

Where “event_start_date” and “event_end_date” are meta keys ( i want to use their values, not mine!)

This is what i had so far..

$tEA = array(
    'post_type' => 'event',
    'meta_key' => $metaKey,
    'orderby' => 'meta_value',
    'order' => $order,
    'posts_per_page' => $postPerPage,
    'meta_query' => array(
        array(
            'key' => $metaKey,
            'value' => $today,
            'compare' => "=",
            'type' => 'DATE'
        ),
        array(
            'key' => '_event_end_time'
        )
    )
);

Related posts

3 comments

  1. This should work for you:

    $tEA = array(
        'post_type' => 'event',
        // you dont need meta_key as you use meta_query
        //'meta_key' => $metaKey,
        'orderby' => 'meta_value',
        'order' => $order,
        'posts_per_page' => $postPerPage,
        'meta_query' => array(
            array(
                'key' => $metaKey,
                // value should be array of (lower, higher) with BETWEEN
                'value' => array('START_DATE', 'END_DATE'),
                'compare' => 'BETWEEN',
                'type' => 'DATE'
            ),
        )
    );
    

    Note that START_DATE and END_DATE should be in MySQL date format YYYY-MM-DD

  2. Didn’t test it, but what about this?

    $tEA = array(
        'post_type' => 'event',
        'meta_key' => $metaKey,
        'orderby' => 'meta_value',
        'order' => $order,
        'posts_per_page' => $postPerPage,
        'meta_query' => array(
            array(
                'key' => 'event_start_date',
                'value' => 'VALUE_THAT_I_WANT',
                'compare' => '>='
            ),
            array(
                'key' => 'event_end_date',
                'value' => 'VALUE_THAT_I_WANT',
                'compare' => '<='
            ),
            array(
                'key' => '_event_end_time'
            )
        )
    );
    

    I am not sure if you needed the other compare, if you do, just prepend it 😛

  3. Since WP 3.7 you can pass ‘date_query’ as an argument.

    Example that returns posts from January 1st to February 28th:

    $args = array(
        'date_query' => array(
            array(
                'after'     => 'January 1st, 2013',
                'before'    => array(
                    'year'  => 2013,
                    'month' => 2,
                    'day'   => 28,
                ),
                'inclusive' => true,
            ),
        ),
        'posts_per_page' => -1,
    );
    $query = new WP_Query( $args );
    

    Code taken from https://codex.wordpress.org/Class_Reference/WP_Query

Comments are closed.