How to make WordPress custom loop with pagination

How to make WordPress custom loop with pagination

Default pagination of WordPress does not work with any type of custom loops created with the help of WP_Query. So if we create a custom post type loop with WP_Query then it does not have the WordPress pagination functions like previous_posts_link(), next_posts_link(), and paginate_links().

By learning how to create a WordPress custom loop with pagination is great but You won’t always want to use the default query on your page, so setting up a custom query on a page is quite handy. This is especially useful for times when you want to display all posts on a static page or in a shortcode, and you want to limit those posts to certain parameters.

What is WP_Query?

WP_Query is one of the most important classes in WordPress which used mostly for showing custom post types loop by the developers. since it gives you access to the posts, pages, and custom post types in the database.

Because we don’t have to write complex SQL queries for the database in order to get the needed information of posts, pages, or custom post types, because WP_Query will do it all for us.

Now, you have the general idea of WP_Query and its usage, then let us share a simple query of WordPress custom loop with pagination with you.

Fix the paged parameter – which is the current page number taken from the main query

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

Now we will pass this variable to the array of arguments for the custom loop or post loop

$args = array( 
    'post_type' => 'post', 
    'posts_per_page' => get_option( 'posts_per_page' ), // You can enter your count manually. Ex:- 10
    'paged'=> $paged,
); 
$query = new WP_Query( $args );

Now $query has our custom query and also any pagination information passed by WordPress. Then we loop through the query as well

if ($query->have_posts()) :
    // Start looping over the query results.
    while ($query->have_posts()) : $query->the_post();

        $current_id = get_the_ID();
        $featured_img_url = get_the_post_thumbnail_url($post->ID, 'full'); 
        $author_id = $post->post_author;
        $categories = get_the_category(get_the_ID());
        ?>
        <a href="<?php the_permalink(); ?>">
            <img src="<?php echo $featured_img_url; ?>" alt="Awesome Image">
        </a>
        <div class="post-date"><?php echo get_the_date( 'F j, Y' ); ?> </div>
        <h3 class="post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        <div class="post-author">By <a><?php the_author_meta( 'user_nicename' , $author_id ); ?> </a></div>
        <div class="post-cat">
            <?php foreach ( $categories as $key => $value) { echo $value->category_nicename; } ?>
        </div>
        <?php 
    endwhile;
endif;
wp_reset_query();

And we will add pagination links just after the end of endwhile loop

<div class="nav-links">
    <?php
    // Create custom pagination links
    $big = 999999999; // Set an arbitrarily large number
    $pagination = paginate_links(array(
        'base'      => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format'    => '?paged=%#%',
        'current'   => max(1, get_query_var('paged')),
        'total'     => $query->max_num_pages,
        'type'      => 'array',
        'prev_text' => '«',
        'next_text' => '»',
        ));

        // Output the pagination links
        if ($pagination) {
            echo '<div class="pagination">';
                foreach ($pagination as $link) {
                    echo '<span class="page-link">' . $link . '</span>';
                }
            echo '</div>';
        }
    ?> 
</div>

In this example, we set the type parameter to ‘array’, which will return an array of pagination links instead of a string. We then loop through the array and output each link with our own HTML markup. We also set the prev_text and next_text parameters to customize the previous and next links.

You can customize the HTML markup of the pagination links by modifying the code inside the foreach loop.

Now, our full custom query, with pagination links will look like this:

function post_grid() 
{  
    ob_start();

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

    $args = array( 
        'post_type' => 'post', 
        'posts_per_page' => get_option( 'posts_per_page' ), // You can enter your count manually. Ex:- 10
        'paged'=> $paged,
    ); 

    $query = new WP_Query( $args );

    if ($query->have_posts()) :

        // Start looping over the query results.
        while ($query->have_posts()) : $query->the_post();

            $current_id = get_the_ID();
            $featured_img_url = get_the_post_thumbnail_url($post->ID, 'full'); 
            $author_id = $post->post_author;
            $categories = get_the_category(get_the_ID());
            ?>
            <a href="<?php the_permalink(); ?>">
                <img src="<?php echo $featured_img_url; ?>" alt="Awesome Image">
            </a>
            <div class="post-date"><?php echo get_the_date( 'F j, Y' ); ?> </div>
            <h3 class="post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
            <div class="post-author">By <a><?php the_author_meta( 'user_nicename' , $author_id ); ?> </a></div>
            <div class="post-cat">
                <?php foreach ( $categories as $key => $value) { echo $value->category_nicename; } ?>
            </div>
            <?php 
        endwhile;
        ?>

        <div class="nav-links">
            <?php
            // Create custom pagination links
            $big = 999999999; // Set an arbitrarily large number
            $pagination = paginate_links(array(
                'base'      => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
                'format'    => '?paged=%#%',
                'current'   => max(1, get_query_var('paged')),
                'total'     => $query->max_num_pages,
                'type'      => 'array',
                'prev_text' => '«',
                'next_text' => '»',
            ));

            // Output the pagination links
            if ($pagination) {
                echo '<div class="pagination">';
                    foreach ($pagination as $link) {
                        echo '<span class="page-link">' . $link . '</span>';
                    }
                echo '</div>';
            }
            ?> 
        </div>
        <?PHP
    endif;
    wp_reset_query();
    return ob_get_clean(); 
}
add_shortcode('post_grid', 'post_grid');

Thats it! Now you can use this shortcode [post_grid] to show wordpress custom loop with pagination.

Leave a Reply

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

The link has been Copied to clipboard!