WordPress custom post type archive page wp_query pagination not working

I have created an archive page for my ‘Event’ custom post ape called archive-event.php.
I used the content from the standard archive.php template and it listed my 4 events in the order they were posted.

The next step was to change the order by the custom field event_date. I did this no problems. Then I wanted to not show any events that event_date had passed. The below code does this perfectly.

Read More

The issue I now have is my pagination is all messed up. I have the default reading settings set to 2 posts per page and I have a ‘Load more’ button to bring up the next two.

When I click ‘Load more’ it duplicates the two events already showing. Any ideas where I’ve gone wrong?

<?php 
$today = date("Ymd");
$args = array (
    'post_type'      => 'event',
    'meta_key'       => 'event_date',
    'orderby'        => 'meta_value', 
    'order'          => 'ASC',
    'meta_query'     => array(
                            array(
                                'key' => 'event_date',
                                'value' => $today,
                                'type' => 'numeric',
                                'compare' => '>=',
                                )
                            ),
                        );
$wp_query = new WP_Query( $args );

while( $wp_query->have_posts() )
{
$wp_query->the_post(); 
?>

         <div>Content goes here</div>


<?php } wp_reset_postdata(); ?>

Related posts

Leave a Reply

1 comment

  1. Depending on how the plugin builds the UI it may or may not be respecting the pagination functionality built into WordPress.

    Try forcing the paged setting into your query like so:

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array (
        'post_type'      => 'event',
        'paged'          => $paged, // this will be set to what WordPress thinks is the proper page to start
        'meta_key'       => 'event_date',
        'orderby'        => 'meta_value', 
        'order'          => 'ASC',
        'meta_query'     => array(
                                array(
                                    'key' => 'event_date',
                                    'value' => $today,
                                    'type' => 'numeric',
                                    'compare' => '>=',
                                    )
                                ),
                            );
    

    Next, if this still doesn’t work, you can test the assumption that the paged parameter isn’t working for some reason by changing the default paged value like so (again, just to test):

    $paged = 2; // just force it to start on the second page to see if that works
    

    If the above test works, I would say that get_query_var() believes you’re on the first page.