I have a website with 100 posts of a custom post type. On the single pages of each post, I would like to have a “Previous” and “Next” link to quickly jump to, you guessed it, the previous or next post.
I thought that was going to be easy, and I made these links:
<?php $prev_post = get_previous_post();
if ($prev_post) {
echo '<a rel="prev" href="' . get_permalink($prev_post->ID) . '">Previous</a>';
} ?>
<?php $next_post = get_next_post();
if ($next_post) {
echo '<a rel="next" href="' . get_permalink($next_post->ID) . '">Next</a>';
} ?>
Except those does not work. Instead of a hundred posts I can navigate through, it only allows me to jump through 5 posts. And random ones too: it goes from #1 to #15, then #40, #58, #80. Or if I decide to start from #100 and click previous, it goes to #79, then #40, #39 and #1.
It’s all very random. I have no clue what order this is and why it does not have all the posts.
Ideally I would like to go through the posts in alphabetical order of their slug. Ignoring taxonomy.
Anyone know how to do this? Thanks!
CodePudding user response:
Try this , but replace the post type.
if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', '← Previous project');
} else {
$last = new WP_Query('post_type=project&posts_per_page=1&order=DESC'); $last->the_post();
echo '<a href="' . get_permalink() . '">← Previous project</a>';
wp_reset_query();
};
if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', 'Next project →');
} else {
$first = new WP_Query('post_type=project&posts_per_page=1&order=ASC'); $first->the_post();
echo '<a href="' . get_permalink() . '">Next project →</a>';
wp_reset_query();
};
CodePudding user response:
Looking more into it, I managed to solve it like that:
<?php
$criteria = array(
'post_type' => 'data_type',
'orderby' => 'slug',
'order' => 'ASC',
'posts_per_page' => -1
);
$posts = get_posts($criteria);
$ids = array();
foreach ($posts as $thepost) {
$ids[] = $thepost->ID;
}
$index = array_search($post->ID, $ids);
$previd = $ids[$index - 1];
$nextid = $ids[$index 1];
if ($previd) { ?>
<a rel="prev" href="<?php echo get_permalink($previd) ?>">Previous</a>
<?php }
if ($nextid) { ?>
<a rel="next" href="<?php echo get_permalink($nextid) ?>">Next</a>
<?php } ?>
The limit of 5 posts was fixed with 'posts_per_page' => -1
. The rest seems too complex for what is actually needed. If anyone knows of a simpler way closer to get_previous_post()
I initially tried, I’m still interested.