Pagination on custom post type not working

I’m having a hard time getting pagination to work with my custom post type query.

The standard “previous_posts_link()” and “next_posts_link();” aren’t working. And through a bit of testing, I’ve noticed neither “get_query_var(‘page’)” or “get_query_var(‘paged’)” are working. Also, adding “/page/2/”, “/2/”, or “/?page=2” isn’t finding a page.

Any suggestions?

if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } else if ( get_query_var('page') ) {$paged = get_query_var('page'); } else {$paged = 1; }

$args = array('post_type' => 'directory',
'posts_per_page' => 2,
'paged' => $paged
);

$my_query = new WP_Query($args);

while ($my_query->have_posts()) {
    $my_query->the_post();
    // do stuff
}
previous_posts_link();
next_posts_link();

Answer

Fixed it by changing the page’s name (more so the page’s URL) so that it did not match the post type name, which causes rewrite problems.

I also learned that previous_posts_link(); and next_posts_link(); as well as wp_paginate() rely on the query variable being named “$wp_query”, so “$my_query” doesn’t work.

Here’s my fixed code:

if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } else if ( get_query_var('page') ) {$paged = get_query_var('page'); } else {$paged = 1; }

$args = array('post_type' => 'directory',
'posts_per_page' => 2,
'paged' => $paged
);

$wp_query = new WP_Query($args);

while ($wp_query->have_posts()) {
    $wp_query->the_post();
    // do stuff
}
previous_posts_link();
next_posts_link();

Attribution
Source : Link , Question Author : DaveP , Answer Author : DaveP

Leave a Comment