Support » Developing with WordPress » I can’t get pagination to work in WP query

  • shtarley

    (@shtarley)


    This is what my current wordpress post query looks like:

    <?php
        $new_loop = new WP_Query( array(
        'post_type' => 'news',
        'posts_per_page' => 5 
        ) );
    ?>

    I want to add the following pagination to it:

    <?php the_posts_pagination( array(
        'mid_size' => 2,
        'prev_text' => __( 'Prev'),
        'next_text' => __( 'Next'),
    ) ); ?>

    I googled for various solutions. Everywhere it said to add “paged” to the array, like so:

    <?php
        $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;**
        $new_loop = new WP_Query( array(
        'post_type' => 'news',
        'paged' => $paged,**
        'posts_per_page' => 5 // put number of posts that you'd like to display
        ) );
    ?>

    However, this does not work. How can I get the pagination to work in a custom wordpress post query?

Viewing 2 replies - 1 through 2 (of 2 total)
  • leogermani

    (@leogermani)

    the_posts_pagination() function works with the main global $wp_query object, it is not looking to your custom query.

    One thing you could do is temporarily overwrite the global $wp_query variable with your own WP_Query instance and restore it afterward with wp_reset_query.

    Moderator bcworkz

    (@bcworkz)

    Check out the examples in the User Contributed Notes section for the paginate_links() documentation.

    Another approach would be to modify the default query through the “pre_get_posts” action. Then WP will handle pagination for you using the usual pagination function that is probably already on your template.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.