wordpress ajax pagination with history

(premise: this is a pretty noob question)

Hi guys,
I am try to code a good ajax navigation/pagination for WordPress.
Currently I am trying to append the new page articles instead of replacing the old ones.

In archive.php I’ve replaced <?php the_posts_navigation(); ?> with

<nav class="navigation posts-navigation" role="navigation">
    <div class="nav-links">
        <div class="nav-previous">
            <?php next_posts_link(); ?>
        </div>
    </div>
</nav>

since I want to display only the “Next page” link (which I will style in a button later).

And in my js file I have

$('.nav-previous a').live('click', function(e){
    e.preventDefault();
    $('.navigation').remove(); // Removing the navigation link at the bottom of the first articles
    var link = $(this).attr('href');
    $.get( link, function(data) {
        var articles = $(data).find('.archive-container');
        $('#primary').append(articles);
    });

});

It is not that clear to me how to implement history handling in a context like this. I’d like to give users the possibility to scroll up to previous results when clicking on the back button and to keep the results when someone clicks on an article and then goes back to the results.

Now, if I use something like window.history.pushState('', '', link); at the end of the click function above, it changes the URL when pushing the link to see the next articles. And this is correct. But, if I click on an article (e.g. of /page/2) to see it and then I click on the back button, it shows only the results of the page containing that article (that is /page/2 in my example). I’d like to show again all the articles the user saw before leaving the archive page instead.

At the moment I’m also working with window.localStorage to reach the goal, but I’d like to understand if it could be feasible only with history and how to do it.


Source: wordpress

Leave a Reply