Support

Account

Home Forums General Issues List posts by date picker with pagination Reply To: List posts by date picker with pagination

  • @hube2 Wow! Thanks for all these examples and explanations!

    Here’s what I have tried on a CPT archive page using pre_get_posts. It works fine for the first page but fails on any subsequent pages (example.com/events/page/2). My guess is that it has to do with my conditional statement failing for any pages other than page 1. Any ideas/suggestions/fixes of my mess?

    I’m trying to get each page of the archive show only events for a specific month, starting with the current month. So page 1 = May 2021, page 2 = June 2021, and so on…

    function custom_events_query( $query ) {
    
        if (  $query->is_main_query() && !is_admin() && is_post_type_archive('event')) {
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $query->set( 'post_type', 'event' );
            $query->set( 'meta_key', 'event_date' );
            $query->set( 'orderby', 'meta_value' );
            $query->set( 'order', 'ASC' );
            $query->set( 'posts_per_page', -1 );
            $query->set( 'paged', $paged );
            if($paged == 1) {
                $datequery = date('Ymd');
                $year = date('Y');
                $month = date('m');
                $meta_query_two = array(
                    'relation' => 'AND',
                    array(
                        'key' => 'event_date',
                        'value' => $datequery,
                        'compare' => '>='
                    ),
                    array(
                        'key' => 'event_date',
                        'value' => $year.''.$month.'31',
                        'compare' => '<='
                    )       
                );
            } else {
                $today = date('Ymd');
                $thisMonth = date('m', strtotime($today));
                $year = date('Y', strtotime($today));
                $month = date('m', strtotime($today.'+'.$paged.' month'));
                $datequery = date('Y'.$month.'01');
                $meta_query_two = array(
                    'relation' => 'AND',
                    array(
                        'key' => 'event_date',
                        'value' => $datequery,
                        'compare' => '>='
                    ),
                    array(
                        'key' => 'event_date',
                        'value' => $year.''.$month.'31',
                        'compare' => '<='
                    )       
                );
            }
            $query->set( 'meta_query', $meta_query_two );
        }
    
        return $query;
    }
    add_filter( 'pre_get_posts', 'custom_events_query' );