How to make pagination via ajax use the correct pagination links and not something like admin-ajax.php/page/n?

Viewed 221

I'm trying to change regular pagination links to work via ajax, since my archive page uses also some filters that work with ajax. It works but only the first time, once it re generates the pagination links, they all link to admin-ajax.php/page/n instead of my-archive/page/n.

I have added a click handler to the pagination links, so that when you click on a link it doesn't navigate away, instead if pulls the paged data via an ajax request, which also re builds the pagination links -- that's where the admin-ajax.php part of the href comes from.

Is there a way to generate those links and forcing them to use the archive url as base instead of admin-ajax.php?

I'm using Timber, here's what I have:

    $context = Timber::context();

    ob_start();
    Timber::render('02-molecules/resource-listing/resource-listing.twig', $context);

    $results = array(
        'html' => ob_get_clean(),
    );

My resource-listing.twig file has the list of the posts and also the pagination links:

{% for post in posts %}
    <li class="m-resource__listing" id="resource-{{post.ID}}">
        <a href="{{post.link}}" title="{{post.preview.read_more(false)}}">
            {{post.title}}
        </a>
    </li>
{% endfor %}


{% include '03-organisms/pagination/pagination.twig' with { pagination: posts.pagination({show_all: false, mid_size: 3, end_size: 2}) } %}
2 Answers

Are you using e.preventDefault() to prevent the page from loading? The solution for me was altering my click event handler in my ajax JS file from

$(selector).click(function());

to

$([selector that is static on the page]).on('click', '[selector of pagination link that gets dynamically loaded via AJAX]', function());

The URLs still have admin-ajax.php in them but the correct jQuery event handler is preventing the pages from loading on click.

This post and its' comments are what helped me resolve my issue: Click event doesn't work on dynamically generated elements

I ended up replacing the ajax url with my archive url in the backend to each of the pagination links.

Related