Pagination when using wp_query?

<!-- query -->
<?php
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    $query = new WP_Query( array(
        'category_name' => 'investor-news',
        'posts_per_page' => 2,
        'paged' => $paged
    ) );
?>

<?php if ( $query->have_posts() ) : ?>

<!-- begin loop -->
<?php while ( $query->have_posts() ) : $query->the_post(); ?>

    <h2><a href="https://wordpress.stackexchange.com/questions/254199/<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
    <?php the_excerpt(); ?>
    <?php echo get_the_date(); ?>

<?php endwhile; ?>
<!-- end loop -->


<!-- WHAT GOES HERE?????? -->


<?php wp_reset_postdata(); ?>

<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

I’ve tried everything to achieve pagination on this static page using the wp_query function but without any luck. There’s a comment in this script called WHAT GOES HERE?????… so what goes here?

This is on a static page that is not the front page or the posts page.

4

Replace <!-- WHAT GOES HERE?????? --> with the pagination code below:

<div class="pagination">
    <?php 
        echo paginate_links( array(
            'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
            'total'        => $query->max_num_pages,
            'current'      => max( 1, get_query_var( 'paged' ) ),
            'format'       => '?paged=%#%',
            'show_all'     => false,
            'type'         => 'plain',
            'end_size'     => 2,
            'mid_size'     => 1,
            'prev_next'    => true,
            'prev_text'    => sprintf( '<i></i> %1$s', __( 'Newer Posts', 'text-domain' ) ),
            'next_text'    => sprintf( '%1$s <i></i>', __( 'Older Posts', 'text-domain' ) ),
            'add_args'     => false,
            'add_fragment' => '',
        ) );
    ?>
</div>

WordPress comes with a handy function called paginate_links() which does the heavy lifting. In the example above, the custom WP_Query object $query is used instead of the global $wp_query object.

Leave a Comment