I'm trying a new approach to paginate posts returned in a category.php file. I want to see snippets of 10 posts at a time. Filename is category-xyz.php and this worked before I changed to this method, although I was using showposts=200 and it was returning all 180 posts in that category.
I changed method because several calls I used were deprecated (eg showposts) or not advised. I am using this post's solution for reference:
How to fix pagination for custom loops?
Here's my code:
<?php
// Define custom query parameters
$custom_query_args = array(
'cat' => 76,
'posts_per_page' => 5
);
// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $custom_query;
// Output custom query loop rather than use wp_query
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
// Loop output goes here
?>
<div class="pcrmbimgholder">
<a href="<?php the_permalink() ?>" rel="bookmark"><img src="<?php echo pcrmbimagegrab() ?>" alt="<?php the_title(); ?>" /></a>
</div>
<h2><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<?php the_content_limit(190, ""); ?>
<?php $customField = get_post_custom_values("price");
if (isset($customField[0])) {
echo "<strong>Price: ".$customField[0];
echo " </strong>";
} else {
;
}
?>
<?php $customField = get_post_custom_values("sku");
if (isset($customField[0])) {
echo "| Stock Reference: ".$customField[0] . "   ";
} else {
;
}
?>
<a class="postbutton" href="<?php the_permalink() ?>" rel="bookmark"><span>View</span></a><div class="separator"></div>
<?php
endwhile;
endif;
// Reset postdata
wp_reset_postdata();
// Custom query loop pagination
previous_posts_link( 'Older Posts' );
next_posts_link( 'Newer Posts', $custom_query->max_num_pages );
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
I have also tried this because I am not sure which parameters I need in the custom query array:
// Define custom query parameters
$custom_query_args = array(
'cat' => 76,
'posts_per_page' => 5,
'max_num_pages' => 20,
'paged' => $paged,
);
The pagination link goes to /category/category-name/page/2/ which results in a 404 error. Any ideas why?
$custom_query->while ( have_posts() ) :
should be written aswhile ( $custom_query->have_posts() ) :
. It was wrong in the source Answer too.