Skip to content

WordPress Pagination Code for Posts

Last update: October 11, 2022
Tested up to: WordPress 6.0.2

FUNCTIONALITY:

  • This code will query and display WordPress posts with numeric pagination
  • Works with any WordPress theme or child-theme
  • Filters through posts, custom post types, categories, tags, authors etc. (general arguments array)
  • Works on posts page (blog), standard pages and template based pages (such as archives or search results)
  • Filters through WordPress pagination arguments array

INSTRUCTIONS:

  • Copy and paste the code below into the WP template file you want to edit
  • Tweak the code according to your needs
    <?php

    $currentPage = get_query_var('paged');


    // General arguments

    $posts = new WP_Query(array(
        'post_type' => 'post', // Default or custom post type
        'posts_per_page' => 10, // Max number of posts per page
        'category_name' => 'My category', // Your category (optional)
        'paged' => $currentPage
    ));


    // Top pagination (pagination arguments)

    echo "<div class='page-nav-container'>" . paginate_links(array(
        'total' => $posts->max_num_pages,
        'prev_text' => __('<'),
        'next_text' => __('>')
    )) . "</div>";


    // Content display

    if ($posts->have_posts()) :
        while ($posts->have_posts()) :
            $posts->the_post();
            echo "<div class='post-wrap'>";
            the_title();
            the_content();
            echo "</div>";
        endwhile;
    endif;


    // Bottom pagination (pagination arguments)

    echo "<div class='page-nav-container'>" . paginate_links(array(
        'total' => $posts->max_num_pages,
        'prev_text' => __('<'),
        'next_text' => __('>')
    )) . "</div>";

    ?>

Category pagination

In case you would like to use this code on your category or tag template to get category pagination, simply add the following line above the “general arguments” section:

$taxonomy = get_queried_object();

And inside “general arguments” section change

'category_name' => 'My category',

to

'category_name' => $taxonomy->slug,

(or in case of a tag template)

'tag' => $taxonomy->slug,

Search pagination

In case you would like to use this code on your search template to get search pagination, simply add the following line above the “general arguments” section:

$taxonomy = get_search_query();

And inside “general arguments” section change

'category_name' => 'My category',

to

's' => $taxonomy,

POSSIBLE ISSUE

In case you are trying to use this code to paginate custom post type entries, you might have a situation in which the pages are giving you error 404. Luckily, the solution is very simple. Go to “WordPress settings -> Reading” and set the “Blog pages show at most” value to be LOWER than your “posts_per_page” value.

Published inBlogCodeTutorialsWordPress