Query & Display WordPress Posts (with Pagination)

July 11, 2018 | by Mihovil Mikulec

FUNCTIONALITY:

  • Will query and display posts with pagination
  • Should work 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)
  • Filters through 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_excerpt();
            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>";

    ?>

In case you would like to use this snippet on your category or tag template and make it load only posts related to the current taxonomy (category or tag), simply add the following line above the “General arguments” section:

$taxonomy = get_queried_object();

And in general arguments section edit

'category_name' => 'My category',

to

'category_name' => $taxonomy->slug,

(or in case of a tag template)

'tag' => $taxonomy->slug,

Last updated: July 19th 2018