Search code examples
phpwordpresscustom-post-typetaxonomy

Next and previous post link in same terms custom taxonomy


I've created a custom taxonomy => cat-blog in my custom post => blog, cat-blog have 4 terms and each terms have list of post belong to that term

Example of terms:

- City Updates (4 post belong)
- Home Tips (6 post belong)
- Real Estate Guide (8 post belong)
- Real Estate Industry (9 post belong)

and using this query

<?php
     $query = new WP_Query(array('posts_per_page' => 2, 'post_type' => 'blog', 'blog-cat' => get_the_term_list( $post->ID, 'blog-cat' )));
     while ($query->have_posts()) : $query->the_post();
     ?>

   <?php 
// content here
?>

    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
 <?php

 ?>

to display 2 post in same category, AND I just want to put next and prev pagination, so I can navigate the rest of the post, belong to that term.


Solution

  • Don't ever change the main query for a custom query on archive pages and on the home page. The main query already does what you want to do. Trying to run a custom query to try and get the same result is like reinventing the wheel. It also causes problems with pagination

    SOLUTION

    • First, remove your custom query, and return to the main loop. The following is all you need in your taxonomy.php

      if( have_posts() ) {
         while( have_posts() ) {
           the_post();
      
           //REST OF YOUR LOOP
      
         }
      }
      
    • Use pre_get_posts in conjuction with the conditional tags if you need to alter the main query. For instance, if you need 2 posts per page on your taxonomy page, do the following in functions.php

      function so26499451_custom_ppp( $query ) {
          if ( !is_admin() && $query->is_tax() && $query->is_main_query() ) {
              $query->set( 'posts_per_page', '2' );
          }
      }
      add_action( 'pre_get_posts', 'so26499451_custom_ppp' );
      

    You can now paginate as normal without any problems. You will now see two posts from the specific term that you clicked on per page on your taxonomy.php.