1
votes

I am trying to display results using multiple custom fields while ordering the results by the first custom field (startdate). The recommendations that I have seen led me to try this:

$args = array(
    'category_name' => 'Events',
    'posts_per_page' => 6,
    'meta_key' => 'startdate',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'startdate',
            'value' => $date,
            'compare' => '>='
        ),
        array(
            'key' => 'closedate',
            'value' => $date,
            'compare' => '>='
        )
    ),
    'orderby' => 'meta_value',
    'order' => 'desc'
);

The problem is that without the meta_key parameter the results filter by the default, the date of the post. When I add the meta_key parameter to sort the results, I get every post with a meta_key equal to startdate. It seems that by adding those meta_key parameter the statement completely ignores the conditions in the meta_query array. How do I get the query to sort by startdate without pulling all of the posts that have a meta_key equal to startdate?

1

1 Answers

3
votes

The solution:

$args = array(
'category_name' => 'Events',
'posts_per_page' => 6,
'meta_key' => 'startdate',
'meta_compare' => '>=',
'orderby' => 'meta_value',
'meta_value' => $date,
'order' => 'DESC',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'startdate',
            'value' => $date,
            'compare' => '>='
       ),
        array(
            'key' => 'closedate',
            'value' => $date,
            'compare' => '>='
        )
    )
);

Essentially, the meta_key argument creates a join in the MySQL statement. The join is not affected by the conditions stated in the meta_query part of the argument. The Codex enumerates parameters to filter the join. I wanted my results to sort by startdate for all dates >= the variable $date. By adding 'meta_compare' => '>=' and 'meta_value' => $date to my $args array I was able to filter the results as I wanted.