Pregunta

I'm looking to create an infinitely looping 'next post' link at the bottom of a post that only links to posts in that category.

So if I have three posts in the same category – 1, 2 and 3 – it should work as follows:

  • clicking the link on post 1 should take me to post 2
  • clicking the link on post 2 should take me to post 3
  • clicking the link on post 3 should take me to post 1

I've got code to loop through all posts in this way, but am stuck on how to edit it so that it only loops through posts with the same category as the current post.

if( get_adjacent_post(true, '', false) ) { 
next_post_link($format = '%link', $link = 'Next Article', $in_same_term = true);
} else { 
$thiscat = get_the_category();
$last = new WP_Query(array('query' => 'posts_per_page=1&order=ASC',
'category_name' => $thiscat)); $last->the_post();
    echo '<a href="' . get_permalink() . '">Next Article</a>';
wp_reset_query();
};
¿Fue útil?

Solución

based on the docu:

'infinitely looping 'next post' link at the bottom of a post that only links to posts in that category'

if( get_adjacent_post(true, '', false, 'category') ) {
   next_post_link($format = '%link', $link = 'Next Article', $in_same_term = true, $taxonomy = 'category'); 
} else { 
   $thiscat = get_the_category(); 
   $catslug = $thiscat[0]->slug; 
   $last = new WP_Query( array( 
      'posts_per_page' => 1, 
      'order' => 'ASC', 
      'category_name' => $catslug  
    ) ); 
   $last->the_post(); 
   echo '<a href="' . get_permalink() . '">Next Article</a>'; 
   wp_reset_postdata(); 
}
Licenciado bajo: CC-BY-SA con atribución
scroll top