1

I have the following code where I want to sort by meta key "event_date" and only display posts after todays date and 3 weeks ahead. Somehow nothing happens, even when I'm stripping down the WP Query to just post type and order, nothing gets printed ud, the scripts just dies where the code is inserted.

<?php $events_args = array(
    'meta_query' => array(
        array(
            'key' => 'event_date',
            'value' => date('d-m-Y', strtotime("+3 weeks")),
            'compare' => '<',
            'type' => 'DATE'
        )
    ),
    'posts_per_page' => 3, 
    'post_type' => 'event', 
    'meta_key' => 'event_date', 
    'orderby' => 'meta_value', 
    'order' => 'ASC'
    ); ?>
<?php $upcoming_events = WP_Query($events_args); ?>
<?php if($upcoming_events->have_posts()): while($upcoming_events->have_posts()): $upcoming_events->the_post(); ?>
    <a href="<?php the_permalink(); ?>"><article class="post_block">
        <h2><?php the_title(); ?></h2>
        <p class="date"><?php $date = new DateTime(get_field('event_date')); echo $date->format('d-m-Y'); ?><?php // echo get_the_date('d-m-Y'); ?></p>
        <p class="text"><?php echo get_the_excerpt(); ?></p>
    </article></a>
<?php endwhile; endif; wp_reset_postdata(); ?>

Any idea why nothing gets output? If I run a simple query_posts like:

query_posts('posts_per_page=3&post_type=event&meta_key=event_date&orderby=meta_value&order=DESC');

then it will print out the events, but it will sort after the newest events, and I need to sort on events from today and 3 weeks ahead to display only.

  • Do you have debugging enabled? – Milo Nov 20 '14 at 17:19
  • No, but I just tried turning it on and I found out I've missed "New" in front of WP_Query. Although this doesn't solve my issue, because it just prints out the latest events anyways. The ones with a event date of 2015... :/ I think my meta_query must be wrong, somehow. – Dueify Nov 20 '14 at 17:56
  • your date format is backwards, you have to store it in the form yyyy-mm-dd to sort by date. – Milo Nov 20 '14 at 18:50
  • Thanks. Turned out the date format was wrong like you pointed out. – Dueify Nov 20 '14 at 18:55
  • 1
    See: wordpress.stackexchange.com/a/78048/21376 – s_ha_dum Nov 20 '14 at 20:22
4

Needed to enter correct date format: Ymd or yyyy-mm-dd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.