I’m pulling my hair out over this WordPress Custom Post Type (CPT) pagination problem. I’ve been at it all night and can’t figure it out. Here’s what I’ve got:
I made a CPT called ‘portfolio’ using Custom Post Types UI. The slug is set to ‘works’. I’m trying to show 20 posts per page, but the pagination is acting up.
Here’s a snippet of my code:
$args = array(
'post_type' => 'portfolio',
'posts_per_page' => 20,
'paged' => get_query_var('paged')
);
$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) :
while ($custom_query->have_posts()) : $custom_query->the_post();
// Loop stuff here
endwhile;
echo '<div class="pagination">';
echo paginate_links(array('total' => $custom_query->max_num_pages));
echo '</div>';
wp_reset_postdata();
endif;
When I try to go to page 2, I get a 404 error. I’ve tried different ways to set up the loop and pagination, but nothing’s working. I’m using WordPress 3.7.1.
Any ideas what could be causing this? I’m totally stuck and would really appreciate some help!
I’ve been down this road before, and it’s a real headache. One thing that helped me was modifying the ‘paged’ parameter in your args array. Try this:
‘paged’ => (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1
Also, make sure your .htaccess file is properly set up. Sometimes, server configuration can interfere with WordPress’s ability to handle custom permalinks. If you’re using Apache, check if mod_rewrite is enabled.
Another trick that solved it for me was adding this to my functions.php:
add_action(‘pre_get_posts’, function($query) {
if (!is_admin() && $query->is_main_query() && is_post_type_archive(‘portfolio’)) {
$query->set(‘posts_per_page’, 20);
}
});
This modifies the main query instead of creating a custom one, which can sometimes play nicer with pagination. Hope this helps!
hey mike, i had similar issues. try adding ‘paged’ => get_query_var(‘paged’) ? get_query_var(‘paged’) : 1 to ur args array. also check ur permalinks settings. sometimes flushing permalinks helps. good luck man!
I’ve encountered this issue before, and it can be quite frustrating. One thing to check is your rewrite rules. Make sure you’ve added ‘has_archive’ => true when registering your CPT. Also, try adding ‘rewrite’ => array(‘slug’ => ‘works’, ‘with_front’ => false) to your CPT registration arguments. This ensures your CPT’s URL structure is correct.
After making these changes, don’t forget to flush your permalinks. You can do this by going to Settings > Permalinks and just hitting ‘Save Changes’ without modifying anything.
If that doesn’t work, you might want to consider using the pre_get_posts action to modify the main query instead of creating a custom one. This often resolves pagination issues with CPTs.