Hide past events posts based on custom date field

2019-07-24 02:54发布

I wish to hide past events based on the custom date field I set up.

<?php 
the_post();
// Get 'events' posts
$events_posts = get_posts( array(
'post_type' => 'events',
'posts_per_page' => -4, // Unlimited posts
'orderby' => 'meta_value',
'meta_key' => 'event_date',
'order' => 'ASC'
) );

if ( $events_posts ):
?>

This code is currently showing my events in order, but I want to hide events older than today's date?

2条回答
甜甜的少女心
2楼-- · 2019-07-24 03:25

If you want to filter data by custom post field you have to use meta_query for this

Here is working example:

$args = [
    'post_type' => 'events',
    'posts_per_page' => -1, // Unlimited posts
    'orderby' => 'meta_value',
    'meta_key' => 'event_date',
    'order' => 'ASC',
    'meta_query' => [
        'relation' => 'AND',
        [
            'key' => 'event_date',
            'value' => date('Y-m-d'), //<-- replace this with your correct date format
            'compare' => '>',
            'type' => 'DATE'
        ],
    ],
];

$queryEvent = new WP_Query($args);
if ($queryEvent->have_posts()) :
    /* Start the Loop */
    while ($queryEvent->have_posts()) : 
    $queryEvent->the_post();

    //you post

    endwhile;
endif;

Hope this helps!

Related answer: https://stackoverflow.com/a/42325398/5019802

查看更多
Viruses.
3楼-- · 2019-07-24 03:48

I think you are talking about looping through the $event_posts result while excluding those events whose date is 'less than today'. Which is quite an unoptimized and inappropriate way to achieve what you want. You should let MySQL retrieve events whose date is greater than NOW(). If the event_date field is a DATETIME type, then modify your query to get only events whose 'event_date' is greater than NOW().

    "SELECT events WHERE event_date >NOW()"
查看更多
登录 后发表回答