Lual Lual - 1 year ago 52
Ajax Question

Load specific parts of (WordPress) next posts page via AJAX

What I'm trying to do exactly

I'm creating a custom WordPress site, it displays a "load more posts" button in the pages blog (main), category and search results. When the user clicks this button, the script retrieves the posts in the next page and appends them inside a container. Here's the code:

document.addEventListener("DOMContentLoaded", function() {

// display or not the btn when page is loaded

var morePosts = $("#dom-target").text();

if (morePosts != "true") {

// button functionality

var pageIndex = 1;
var numOfPages = Number($('#numOfPages').text()); // parsed from php
var nextLink = $('#nextLink').text(); // parsed from php


if (pageIndex < numOfPages) {

var nextPosts;
$.get(nextLink+' .post-card', function(data){

// get articles in next page
nextPosts = data;

// append articles

// change value of index and redefine nextLink
nextLink = nextLink.replace(pageIndex+'/',pageIndex+1+'/');

// check if button display is still needed
if (pageIndex == numOfPages) {
$('.load-more').css('transition','all 0s');

The problem: It loads the entire page

I wonder if
has a equivalent for
.load('main url .specific-class')
, because when I try to apply the analogous syntax

$.get(nextLink+' .post-card')

the console threw me

GET http://localhost/blog/page/2/ 404 (Not Found)

Or if there is a way to parse the data (a string) as an HTML document (so I can apply jQuery to the variable that stores the data and get just the post cards instead of the entire page).

Thanks in advance! :)

Answer Source

You have to parse the response yourself which you can do simply by wrapping in $() and using any jQuery method on

$.get(nextLink, function(data){
     var nextPosts = $(data).find('.post-card');