Hide past event messages based on custom date field

I want to hide past events based on a custom date field that I set.

<?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 currently shows my events in order, but I want to hide events older than today's date?

+1
source share
2 answers

If you want to filter the data by custom field posts, you should use meta_queryfor this

Here is a 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: fooobar.com/questions/1016413 / ...

+1
source

, $event_posts, , ", ". , . MySQL , , NOW(). event_date DATETIME, , , "event_date" , NOW().

    "SELECT events WHERE event_date >NOW()"
-1

Source: https://habr.com/ru/post/1016411/


All Articles