Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include pagination in a Wordpress Custom Post Type Query

I have the code below:

<?php $the_query = new WP_Query( 'posts_per_page=30&post_type=phcl' ); ?>

<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

<div class="col-xs-12 file">
    <a href="<?php echo $file; ?>" class="file-title" target="_blank">
        <i class="fa fa-angle-right" aria-hidden="true"></i> 
        <?php echo get_the_title(); ?>
    </a>
    <div class="file-description">
        <?php the_content(); ?>
    </div>
</div>
<?php endwhile; wp_reset_postdata(); ?>

I am trying to use paginate_links Wordpress function but no matter where I put it, I can't make it work. Can someone help me with this?

like image 621
Ganikkost Avatar asked Jan 19 '17 09:01

Ganikkost


People also ask

How do I get pagination page numbers in WordPress?

Since WP 3.9. 0, $paged = get_query_var( 'paged', $default ) allows a second argument with the default value. So, $paged = get_query_var( 'paged', 1 ) or $paged = get_query_var( 'paged', 0 ) (as @Kip noticed) will do.


1 Answers

When querying a loop with new WP_Query set the 'total' parameter to the max_num_pages property of the WP_Query object.

Example of a custom query:

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

$args = array(
    'post_type'=>'post', // Your post type name
    'posts_per_page' => 6,
    'paged' => $paged,
);

$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();

             // YOUR CODE

    endwhile;

    $total_pages = $loop->max_num_pages;

    if ($total_pages > 1){

        $current_page = max(1, get_query_var('paged'));

        echo paginate_links(array(
            'base' => get_pagenum_link(1) . '%_%',
            'format' => '/page/%#%',
            'current' => $current_page,
            'total' => $total_pages,
            'prev_text'    => __('« prev'),
            'next_text'    => __('next »'),
        ));
    }    
}
wp_reset_postdata();
?>

Example of paginate_links parameters adapted to the custom query above:

For more reference please visit this link

like image 89
Purvik Dhorajiya Avatar answered Sep 21 '22 13:09

Purvik Dhorajiya