Jetpack is a plugin that offers wide array of functionalities like statistic, CDN, security, etc.
One of my favorite Jetpack’s module is Infinite Scroll. As the name suggests, it automatically loads more posts when you reached the bottom.
If you want to apply this to normal theme, then you can refer to the official doc.
But for Timber theme, it is a bit tricky. Here’s how:
Step 1: Disable WP_DEBUG
At the time of writing, Infinite Scroll will not work if WP_DEBUG
is set to true. If that’s the case, open your wp-config.php and set it to false.
Step 2: Add ID to Posts Wrapper
In your posts loop, add id="content"
to the direct parent. For example, if you have <ul>
as the parent, then it goes like this:
...
<ul class="posts-list" id="content">
{% for post in posts %}
<li class="post-archive">
...
</li>
{% endfor %}
</ul>
...
Step 3: Move the Loop Into Its Own File
Create a new TWIG file and move the for
loop snippet above into there:
{% for post in posts %}
<li class="post-archive">
<h3><a href="{{ post.link }}">{{ post.title }}</a></h3>
{% if post.thumbnail %}
<a href="{{ post.link }}" class="archive-figure image-fit image-fit--{{ e.ratio }}" tabindex="-1">
<img src="{{ post.thumbnail.src('medium') }}" alt="{{ post.title }}">
</a>
{% endif %}
<p>{{ post.preview.length( e.word_count ).read_more('') }}</p>
<a href="{{ post.link }}" class="button">
Read More
</a>
</li>
{% else %}
<li class="error-message">
<h1>Sorry</h1>
<p>We couldn’t find any posts.</p>
</li>
{% endfor %}
Don’t forget to replace the original one with include
:
...
<ul class="posts-list" id="content">
{% include "_post-loop.twig" %}
</ul>
...
Step 4: Add Theme Support
The module automatically activates if you put infinite-scroll
theme support. You also need to define a render
parameter that tells what to display:
add_action( 'after_setup_theme', 'my_after_setup_theme' );
function my_after_setup_theme() {
add_theme_support('infinite-scroll', [
'render' => 'my_infinite_scroll_render',
'posts_per_page' => '9',
] );
}
function my_infinite_scroll_render() {
$context = [
'posts' => Timber::get_posts(),
];
Timber::render('_post-loop.twig', $context);
}
Done! Your pagination should now be replaced with infinite scroll.
Note: the infinite scroll adds a <div>
wrapper to your loop, so you might need to fix the CSS.
Conclusion
Infinite scrolling makes it easier and cooler to browse your content. But the most fatal disadvantage is losing your Footer.
So if the information in your footer is valuable, don’t use infinite scrolling.
Having trouble implementing it? Let me know in the comment below 🙂