47
<!-- 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="<?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 Answers 4

65

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.

Edit: In response to comment from @mark-in-motion, here's an example of a wrapper function for paginate_links() that I made a while back. You can add this to your theme's functions.php, then call echo my_pagination(); in your template to display pagination.

/**
 * Numeric pagination via WP core function paginate_links().
 * @link http://codex.wordpress.org/Function_Reference/paginate_links
 *
 * @param array $args
 *
 * @return string HTML for numneric pagination
 */
function my_pagination( $args = array() ) {
    global $wp_query;
    $output = '';

    if ( $wp_query->max_num_pages <= 1 ) {
        return;
    }

    $pagination_args = array(
        'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
        'total'        => $wp_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'    => __( '&laquo; Prev', 'text-domain' ),
        //'next_text'    => __( 'Next &raquo;', 'text-domain' ),
        //'prev_text'    => __( '&lsaquo; Prev', 'text-domain' ),
        //'next_text'    => __( 'Next &rsaquo;', 'text-domain' ),
        'prev_text'    => sprintf( '<i></i> %1$s',
            apply_filters( 'my_pagination_page_numbers_previous_text',
            __( 'Newer Posts', 'text-domain' ) )
        ),
        'next_text'    => sprintf( '%1$s <i></i>',
            apply_filters( 'my_pagination_page_numbers_next_text',
            __( 'Older Posts', 'text-domain' ) )
        ),
        'add_args'     => false,
        'add_fragment' => '',

        // Custom arguments not part of WP core:
        'show_page_position' => false, // Optionally allows the "Page X of XX" HTML to be displayed.
    );

    $pagination_args = apply_filters( 'my_pagination_args', array_merge( $pagination_args, $args ), $pagination_args );

    $output .= paginate_links( $pagination_args );

    // Optionally, show Page X of XX.
    if ( true == $pagination_args['show_page_position'] && $wp_query->max_num_pages > 0 ) {
        $output .= '<span class="page-of-pages">' .
                                    sprintf( __( 'Page %1s of %2s', 'text-domain' ), $pagination_args['current'], $wp_query->max_num_pages ) .
                '</span>';
    }

    return $output;
}
4
  • 1
    I think i'm too late. but question is.. why should i write 999999999?
    – MFarooqi
    Mar 20, 2021 at 23:47
  • This is trick to get the results of get_pagenum_link() with %#% instead of the page number (999999999). Mar 26, 2021 at 15:32
  • 1
    Is there a way to put this on functions.php so that you just have to call pageinate_links() and not the whole thing? Jul 13, 2022 at 7:26
  • 1
    @mark-in-motion Sure! Added an example to the answer. Jul 15, 2022 at 18:53
14

This code is for Custom Query Pagination. You can follow the steps to create your own pagination in WordPress.

 <?php
/**
* Template Name: Custom Page
*/
get_header(); ?>

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
  'posts_per_page' => 4,
  'paged' => $paged
);
$custom_query = new WP_Query( $args );
?>
          <!----start-------->
<div class="wrap">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">

<?php
   while($custom_query->have_posts()) :
      $custom_query->the_post();
?>
       <div>
        <ul>
         <li>
           <h3><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h3>
        <div>
          <ul>
        <div><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a></div>
          </ul>
          <ul>
        <p><?php echo the_content(); ?></p>
          </ul>
        </div>
        <div>
          </li>
        </ul>
          </div> <!-- end blog posts -->
       <?php endwhile; ?>
      <?php if (function_exists("pagination")) {
          pagination($custom_query->max_num_pages);
      } ?>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- .wrap -->
          <!----end-------->
        <?php get_footer();

Reference : https://www.wpblog.com/use-wp_query-to-create-pagination/

2
  • Seems function pagination does not exist, please assist Jun 27, 2021 at 0:41
  • @KarueBensonKarue that is because the poster of this answer copy pasted something from another website, and you copy pasted from this website If you go to the source wpblog.com/use-wp_query-to-create-pagination you will see how they explain to define the function pagination() as well
    – user75665
    Feb 21 at 3:54
2

If anyone arrives here attempting to create a wp_query with pagination from inside a shortcode:


add_shortcode('wp_query_pagination_inside_shortcode', 'my_shortcode_function_tag');
if (!function_exists('my_shortcode_function_tag')) {
    function my_shortcode_function_tag($atts)
    {
        ob_start(); // Turn output buffering on
        global $paged;
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $atts = shortcode_atts(
            array(
                'post_type' => 'post',
                // whatever you like
            ),
            $atts
        );
        $args = array(
            'posts_per_page' => 3,
            'paged' => $paged,
            'post_type' => $atts['post_type'],
            'orderby' => 'date',
            'order' => 'DESC',
        );
        $the_query = new WP_Query($args);

        if ($the_query->have_posts()) {
            while ($the_query->have_posts()) {
                $the_query->the_post();
                get_template_part('template-parts/loop');
            } //end while

            $big = 999999999; // need an unlikely integer
            echo paginate_links(
                array(
                    'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
                    'format' => '?paged=%#%',
                    'current' => max(
                        1,
                        get_query_var('paged')
                    ),
                    'total' => $the_query->max_num_pages //$q is your custom query
                )
            );
        } // Pagination inside the endif
        return ob_get_clean(); // Silently discard the buffer contents
        wp_reset_query(); // Lets go back to the main_query() after returning our buffered content
    }
}
1

You can simply use a built-in WP function

<?
the_posts_pagination()
?>

It does the job very well with custom WP_Query

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.