'How to check if at last post and navigate to first post
I have page arrows (Previous and Next ) on every single post however when I reach the last post I want to still keep the Next button which will link to the first post and vice versa if I'm on the first post I want to keep the previous button which would link to last post.
This is my .twig file which currently simply navigates to next or previous post if there is one.
<div class="post-prev">
{% if post.prev %}
<a href="{{ post.prev.link }}">Previous</a>
{% endif %}
</div>
<div class="post-next">
{% if post.next %}
<a href="{{ post.next.link }}">Next</a>
{% endif %}
</div>
and my PHP file which orders posts by date.
$context = Timber::get_context();
$context[ "main_menu" ] = new Timber\Menu('main');
$context['page'] = new TimberPost();
$args = array(
// Get post type project
'post_type' => 'post',
// Get all posts
'posts_per_page' => -1,
// Order by post date
'orderby' => array(
'date' => 'DESC'
)
);
Solution 1:[1]
As DarkBee said check if prev on next properties has some object and if it is not fetch first or last item from a query
$post = new TimberPost();
$next = $post->next ?: Timber::get_posts( ['posts_per_page' => 1, 'order' => 'ASC'] )[0];
$prev = $post->prev ?: Timber::get_posts( ['posts_per_page' => 1, 'order' => 'DESC'] )[0];
$context['page'] = $post;
$context['next'] = $next;
$context['prev'] = $prev;
Note: Timber::get_posts() may return bool or null so there may be an error when getting first element. So you may check it also. But if you sure there are plenty of posts and some result will be returned it is OK
In a view file no need to check if next/prev post exists
<div class="post-prev">
<a href="{{ prev.link }}">Previous</a>
</div>
<div class="post-next">
<a href="{{ next.link }}">Next</a>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ihar Aliakseyenka |
