Super Loopers - Custom Events Page

I used your Super Loopers tutorial in Max to create a custom events page, it’s working great!

But one issue: The php code you provide here is working great so that events in the past no longer appear on the events page. But it’s not working as intended on the home page, where I’ve built a little “recent posts” looper that is showing the next 2 events – the event in the past is still displaying here.

I’m not sure what I need to do?

Hello @capodanno,

Thanks for writing in!

The given PHP code is this:

// Place this into a custom plugin or into your functions.php

function custom_events_query($query) {
    // Check if we're on the main query and it's the archive for 'events' custom post type
    if (!is_admin() && $query->is_main_query() && is_post_type_archive('events')) {
        // Set the meta query to only show events from today's date onward
        $meta_query = array(
            array(
                'key'     => 'event_start_date',
                'value'   => date('Ymd'),
                'compare' => '>=',
                'type'    => 'DATE'
            )
        );

        // Set the query to order by the event_start_date meta field
        $query->set('meta_key', 'event_start_date');
        $query->set('orderby', 'meta_value');
        $query->set('order', 'ASC');
        $query->set('meta_query', $meta_query);
    }
}

add_action('pre_get_posts', 'custom_events_query');

If you notice in the code above, we have this condition: if (!is_admin() && $query->is_main_query() && is_post_type_archive('events')), which basically means "IF NOT the admin page AND it is the main query AND events post archive ". The code works only in the events archive. You cannot use this on your home page. You would need to modify the condition to make it work. Possibly change the condition into this:
if (!is_admin() && $query->is_main_query()) {

Hope this makes sense.

Thank you! I was thrilled to discover that ChatGPT was able to help me correct the php code, so this is now working properly.

You are most welcome, @capodanno.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.