Skip to content

Instantly share code, notes, and snippets.

@slopesweb
Forked from bebaps/load-posts.js
Created November 21, 2022 23:08
Show Gist options
  • Save slopesweb/c38b3614b2419fd0308816c12c5bc1db to your computer and use it in GitHub Desktop.
Save slopesweb/c38b3614b2419fd0308816c12c5bc1db to your computer and use it in GitHub Desktop.
Load posts into a page using the WP REST API
// This function uses AJAX to run a query.
// It assumes that there are no posts on the page, and they will be loaded by the user on demand.
// // There are no animations added here. For a smoother experience, it is a good idea to add animations to the button (ex. a loading icon during the request), or making the new posts animate in (ex, using Animate.css to fade them into the page)
$(function() {
// Grab the load button, since I only want to run the code if the button is on the page
var ajaxButton = $('#ajax-button');
if (ajaxButton) {
// The AJAX request
var getPosts = function() {
var theData, ajaxContainer, errorStatus, errorMessage;
// Make the request to the REST API
$.ajax({
url: 'http://wordpress.dev/wp-json/wp/v2/posts',
dataType: 'json',
success: function(data) {
// Remove the button if the response returns no items
if ( data.length < 1 ) {
ajaxButton.remove();
}
// Create a place to store exactly what I need
// Alternatively, the response can be filtered to only return the needed data, which is probably more efficient as the following loop wont be needed
theData = [];
// Grab the container where my data will be inserted
ajaxContainer = $('#ajax-div');
// Get only what I need, and store it
for (i = 0; i < data.length; i++) {
theData[i] = {};
theData[i].id = data[i].id;
theData[i].slug = data[i].slug;
theData[i].link = data[i].link;
theData[i].title = data[i].title.rendered;
theData[i].content = data[i].content.rendered;
// Now create the element where this data will live
ajaxContainer.append('<article class="ajax-post"></article>');
}
// For each element I just created, insert the data from my newly built array
$('.ajax-post').each(function(i) {
var $this = $(this);
$this.append('<h3>' + theData[i].title + '</h3>');
$this.append(theData[i].content);
});
},
error: function(jqXHR, textStatus, errorThrown) {
errorStatus = jqXHR.status + ' ' + jqXHR.statusText + '\n';
errorMessage = jqXHR.responseJSON.message;
// Show me what the error was
console.log(errorStatus + errorMessage);
}
});
};
// Actually implement the functionality when the button is clicked
ajaxButton.on('click', function() {
getPosts();
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment