Kishan Jasani

Code, Creativity & Everything I Learn

How pagination works with custom query?

Theme developers can implement pagination using simple links or numbered navigation to guide users through content. The number of posts displayed per page can be adjusted under Settings > Reading in the WordPress dashboard.

WordPress provides built-in pagination functions like previous_post_link() and next_post_link(), which work only with the main query. For custom queries, pagination can be handled using WP_Query with the paged parameter:

$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

$args = array(
  'post_type'      => 'news',
  'posts_per_page' => 4,
  'paged'          => $paged,
);

$custom_query = new WP_Query( $args );

while ( $custom_query->have_posts() ) :
    $custom_query->the_post();
    echo the_title( '<p>', '</p>' );
endwhile;

if ( function_exists( 'pagination' ) ) {
    pagination( $custom_query->max_num_pages );
}

For static pages, use page instead of paged in WP_Query arguments. Here’s an example:

$paged = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;

$args = array(
  'post_type'      => 'page',
  'posts_per_page' => 4,
  'paged'          => $paged, // Use 'page' instead if needed
);

$custom_query = new WP_Query( $args );

while ( $custom_query->have_posts() ) :
    $custom_query->the_post();
    echo the_title( '<p>', '</p>' );
endwhile;

if ( function_exists( 'pagination' ) ) {
    pagination( $custom_query->max_num_pages );
}

Note: Use page instead of paged in get_query_var() and WP_Query when working with static pages.

Leave a Reply

Your email address will not be published. Required fields are marked *