0
0
Wordpressframework~5 mins

Pagination with custom queries in Wordpress

Choose your learning style9 modes available
Introduction

Pagination helps split a long list of posts into smaller pages. Custom queries let you control which posts to show.

You want to show posts from a specific category with pages.
You need to display search results with page numbers.
You want to list custom post types with pagination.
You want to control how many posts appear per page.
You want users to navigate through filtered posts easily.
Syntax
Wordpress
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = [
  'post_type' => 'post',
  'posts_per_page' => 5,
  'paged' => $paged
];
$query = new WP_Query($args);
if ($query->have_posts()) :
  while ($query->have_posts()) : $query->the_post();
    // Display post content
  endwhile;
  // Pagination links
  previous_posts_link('Previous');
  next_posts_link('Next', $query->max_num_pages);
endif;
wp_reset_postdata();
?>

Use paged to track the current page number.

Always reset post data after custom queries with wp_reset_postdata().

Examples
Query posts from the 'news' category with 3 posts per page.
Wordpress
<?php
$paged = max(1, get_query_var('paged'));
$args = [
  'category_name' => 'news',
  'posts_per_page' => 3,
  'paged' => $paged
];
$query = new WP_Query($args);
?>
Query 10 'product' custom post types per page.
Wordpress
<?php
$paged = get_query_var('paged') ?: 1;
$args = [
  'post_type' => 'product',
  'posts_per_page' => 10,
  'paged' => $paged
];
$query = new WP_Query($args);
?>
Sample Program

This code shows 2 posts per page with Previous and Next links to navigate pages.

Wordpress
<?php
/* Template for paginated custom query */
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = [
  'post_type' => 'post',
  'posts_per_page' => 2,
  'paged' => $paged
];
$query = new WP_Query($args);
if ($query->have_posts()) :
  while ($query->have_posts()) : $query->the_post();
    echo '<h2>' . get_the_title() . '</h2>';
  endwhile;
  echo '<div class="pagination">';
  previous_posts_link('Previous');
  next_posts_link('Next', $query->max_num_pages);
  echo '</div>';
else :
  echo 'No posts found.';
endif;
wp_reset_postdata();
?>
OutputSuccess
Important Notes

Make sure your theme supports pagination links for best results.

Use max(1, get_query_var('paged')) to avoid page 0 issues.

Custom queries do not affect the main query, so use wp_reset_postdata() to restore global post data.

Summary

Pagination splits posts into pages for easier reading.

Custom queries let you choose which posts to show.

Use paged parameter and reset post data after your query.