questions

Only display upcoming events in WP Widget

Rate this post

Through a shortcode I placed the following code which is intented to display a random upcoming event in the sidebar. At the moment it displays a random of ALL events. How would I change the code to only display events that are younger than the current date?

        <?php 
// Build a custom query to get posts from future dates.
$querystr = `
    SELECT wposts.* 
    FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE wposts.ID = wpostmeta.post_id
    
    AND wpostmeta.meta_key = 'f21_event_startdate'
AND STR_TO_DATE(wpostmeta.meta_value,'j. M Y') >= CURDATE()
 
AND wposts.post_status = 'publish'
AND wposts.post_type = 'events'

ORDER BY STR_TO_DATE(wpostmeta.meta_value,'j. M Y') RAND
LIMIT 1
`;

$events = $wpdb->get_results($querystr, OBJECT);

 if ($events):
    global $post;
    foreach ($events as $post):
        setup_postdata($post); ?>   
            
            <?php the_field('f21_event_startdate'); ?>
    <h2><a style="color:#1e73be;" href="<?php the_permalink() ?>"><?php the_title(); ?></h2>
    <div style="margin-top:10px; margin-bottom: 10px;"><?php the_post_thumbnail('full'); ?></div></a>
    <b><?php the_field('f21_event_sub_header'); ?></b>
    <?php endforeach;
else : ?>
    <li>Sorry, no events coming up.</li>
<?php endif; ?>

 

✔️Solution:

you can WP_Query(). check the code below.

$args = array(
    'post_type'      => 'events',
    'posts_per_page' => -1,
    'meta_key'       => 'f21_event_startdate',
    'meta_value'     => date('Ymd'),
    'meta_compare'   => '>=',
    'orderby'        => 'rand',
    'order'          => 'ASC'
);

$upcoming_events = new WP_Query( $args );

Leave a Reply

Your email address will not be published.

Back to top button