I want to fetch other posts in WordPress. I can fetch next post on scroll. But when I go to latest post, it fetches nothing. When I go to the second latest post, on scroll it fetches only first post. When I go to the third latest post, it fetches only first and second latest posts. And so on. I want to fetch all posts on scroll, one by one.
<?php
$next_post = get_next_post();
if ($next_post) :
$next_post_url = get_permalink($next_post->ID);
?>
<a id="next-post-link" href="<?php echo esc_url($next_post_url); ?>"
style="display: none;">
</a>
<?php endif; ?>
JavaScript
document.addEventListener("DOMContentLoaded", function()
{
let loading = false;
window.addEventListener("scroll", function()
{
let nextPostLink = document.getElementById("next-post-link");
if (!nextPostLink || loading) return;
let scrollPosition = window.innerHeight + window.scrollY;
let documentHeight = document.documentElement.scrollHeight;
if (scrollPosition >= documentHeight - 200)
{
loading = true;
let url = nextPostLink.href;
fetch(url)
.then(response => response.text())
.then(data =>
{
let parser = new DOMParser();
let doc = parser.parseFromString(data, "text/html");
let newPost = doc.querySelector("#post-container .post");
if (newPost)
{
document.getElementById("post-container").appendChild(newPost);
let newNextPostLink = doc.querySelector("#next-post-link");
if (newNextPostLink)
{
nextPostLink.href = newNextPostLink.href;
}
else
{
nextPostLink.remove(); // No more posts
}
// Update URL without reloading
history.pushState(null, "", url);
}
loading = false;
})
.catch(error =>
{
console.error("Error fetching next post:", error);
loading = false;
});
}
});
});