I’ve searched WP Codex and StackExchange and gotten some clues, but I can’t get this query working. I have 2 custom fields associated with each exhibition in Y-m-d format: exstart-date being the start date of the exhibition and exend-date being the ending date.

I can easily display upcoming exhibits and past exhibits, but I cannot get the meta_query right to display current exhibits (with a start date less than or equal to today AND end date greater than or equal to today). The code below displays nothing on the page. Help?

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$today = date('Y-m-d', strtotime('-6 hours'));
query_posts(array(
    'post_type' => 'exhibitions', 
    'posts_per_page' => 6, 
    'paged' => $paged,
    'orderby' => 'title',
    'order' => 'DESC',
    'meta_query'=>array(
        'relation'=>'AND',
        array(
            'key' => 'exstart-date',
            'value' => $today,
            'compare' => '<=',
            'type' => 'CHAR'
            ),
        array(
            'key' => 'exend-date',
            'value' => $today,
            'compare' => '>=',
            'type' => 'CHAR'
            )
        )
    ));
if (have_posts()) :
while (have_posts()) : the_post();

1 Answer
1

Here is the code I ended up with that works. I should have mentioned that the query was inside the loop, because when I showed it to Damian Taggart of Mindshare Studios, he noticed that he said I should be using WP_Query instead of query_posts. Thanks to Milo and others for attempting to help me without having all the necessary info.

<?php
     $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
     $today = date('Y-m-d', strtotime('-6 hours'));
     $myquery = new WP_Query(array(
     'post_type' => 'exhibitions', 
     'posts_per_page' => 6,  
     'paged' => $paged,
     'orderby' => 'title',
     'order' => 'ASC',
     'meta_query'=>array(
            'relation'=>'AND',
            array(
                'key' => 'exstart-date',
                'value' => $today,
                'compare' => '<=',
                'type' => 'CHAR'
            ),
            array(
                'key' => 'exend-date',
                'value' => $today,
                'compare' => '>=',
                'type' => 'CHAR'
            )
        )
    ));
    if ($myquery->have_posts()) :
    while ($myquery->have_posts()) : $myquery->the_post();
?>

Leave a Reply

Your email address will not be published. Required fields are marked *