Support » Fixing WordPress » Problem with pagination with categories

  • mcamposs


    Hello, the following code does not work in category.php file (it only works archive.php), in the pagination when I click next, it sends me to the home page. Can you helpme please?

    $idcat = get_query_var('cat');
     $args = array (
    	'post_type'              => 'post',
    	'post_status'            => 'publish',
    	'pagination'             => true,
    	'paged'          	 => $paged,
    	'posts_per_page'         => 5, //not inclue archive.php
    	'order'                  => 'ASC',
    	'orderby'                => 'date',
    $wp_query = new WP_Query($args);
    if ( $wp_query->have_posts() ) :
      while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
    <div class="row mb-3 ml-3 mr-3" style="border-bottom:1px dotted #999;">
    	<div class="row mb-3">
    		<div class="col-md-4">
    		<?php if ( has_post_thumbnail() ) {the_post_thumbnail( 
                    'jumbo_thumbnail', array( 'alt' => 'Responsive image', 'class' => 'img- 
                    fluid rounded' ) ); }?>
    	<div class="col-md-8">
    		<a class="the-title" href="<?php the_permalink(); ?>"><?php 
                    the_title(); ?></a>
    	  <p class="card-text">
    		<a class="the-title" href="<?php the_permalink(); ?>"><?php 
                    the_title(); ?></a>
    		<p class="card-text"><?php the_excerpt(); ?>
    <?php endwhile; ?>
    <div class="row">
    	<div class="col-xs-6">
    		<?php previous_posts_link('<i class="fa fa-arrow-left"></i> <span 
                    class="text">Anterior</span>'); ?>
    	<div class="col-xs-6 text-right">
    		<?php next_posts_link('<span class="text">Siguiente</span> <i class="fa 
                    fa-arrow-right"></i>'); ?>
    <?php	endif;	unset($wp_query); wp_reset_query(); ?>
Viewing 1 replies (of 1 total)
  • Moderator bcworkz


    It’s a lucky coincidence your code works on other templates, it cannot be expected to work reliably at all. The problem is next_posts_link() thinks it is paginating the original main query, but you are doing a custom query which the posts link function knows nothing about. There are two possible solutions.

    1. Coordinate a custom pagination function with your custom query, then use ‘offset’ instead of ‘paged’, which means you need to calculate the actual offset into the results instead of just passing a page number as ‘paged’.


    2. Alter the main query for categories requests to mirror what you are doing in your custom query through the ‘pre_get_posts’ action, then use a normal template loop instead of your custom query. Your callback will need a conditional statement to ensure only category queries are altered. The posts link functions will then properly paginate your query.

Viewing 1 replies (of 1 total)
  • The topic ‘Problem with pagination with categories’ is closed to new replies.