2

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}) } %}
andrux
  • 2,782
  • 3
  • 22
  • 31
  • Did you ever find a solution to this? I'm having the same issue now. – Tyler Hall Apr 29 '21 at 16:32
  • 1
    I think I just did a str_replace from the admin ajax url to the archive url in the backend looping through all pagination links before sending them to the front – andrux Apr 29 '21 at 17:19
  • I considered that but it wouldn't work for my particular setup, unfortunately. I left an answer below in case it helps you too – Tyler Hall Apr 29 '21 at 17:34
  • I already got my setup working, I just forgot to close this question – andrux Apr 29 '21 at 17:43

2 Answers2

1

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Tyler Hall
  • 363
  • 1
  • 2
  • 7
0

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

andrux
  • 2,782
  • 3
  • 22
  • 31