david-s
7/8/2019 - 8:12 AM

PHP Wordpress Pagination

This is the Wordpress way of creating post pagination when using WP_Query.

/**
 * Pagination for blog posts
 * @param $postQuery Query
 */
function soak_insight_listing_pagination($postQuery) {
    $big = 999999999;

    echo '<div class="iblog-listing__pagination-list">' . paginate_links(
        [
            'base'          => str_replace( $big, '%#%', esc_url(get_pagenum_link($big))),
            'format'        => '?paged=%#%',
            'current'       => max( 1, get_query_var('paged') ),
            'total'         => $postQuery->max_num_pages,
            'prev_next'     => true,
            'mid_size'      => 4,
        ]
        ) . '</div>';
}
<?php
$postsPerPageGrid = 2;
$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1;

$categoryName = $_GET['lang'] ? esc_html(trim($_GET['lang'])) : 'uk';
$postArgs = [
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => $postsPerPageGrid,
    'orderby' => 'meta_value_num',
    'paged' => $paged,
    'category_name' => $categoryName,
];

$postQuery = new WP_Query($postArgs);
?>

<div class="blog-listing__list-container">
    // This generates the posts
    <?php if ($postQuery->have_posts()) : ?>
        <?php while ($postQuery->have_posts()) : $postQuery->the_post();
            get_template_part('partials/blog-listing-block');
        endwhile;
        wp_reset_postdata();
        else : ?>
            <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif; ?>
</div>
// This generates the numbered pagination
<div class="blog-listing__pagination">
    <?php
        if (function_exists('soak_insight_listing_pagination')) {
            soak_insight_listing_pagination($postQuery);
        };
    ?>
</div>