Ajax Load
NOTE - I did this without testing so it may not work until I get time to test it. Basically, I wrote it blind. You'll have to adapt slightly to make it work for the bespoke project but the main principle is there
Add a form group to manage state
<form data-archive-state>
<input type="hidden" name="postType" value="team" hidden />
<input type="hidden" name="postsPerPage" value="9" hidden />
<input type="hidden" name="pageNumber" value="1" hidden />
</form>Add an event listener to monitor for a button click or something
document.addEventListner('DOMContentLoaded', () => {
//* Get Button
const button = document.querySelector('button');
//* If no button, stop
if (!button) return;
//* Add click event for button
button.addEventListner('click', async ev => {
//* Get the form state
const form = document.querySelector('[data-archive-state]');
//* Construct FormData
const formData = new FormData(form);
//* Get current page number
let pageNumber = formData.get('pageNumber');
//* Add single page
pageNumber++;
//* Add it back to the form to make sure we keep the state
const pageNumberInput = document.querySelector('input[name="pageNumber"]');
pageNumberInput.value = pageNumber;
//* Get the values we need
const archiveData = {
postType: formData.get('postType'),
postsPerPage: formData.get('postsPerPage'),
pageNumber
};
//* Send to endpoint
const posts = await fetch('/wp-json/SoBold/v1/archive/posts?' + new URLSearchParams(archiveData))
.then(res=>res.json())
.then(res=>{
//* Append the posts here
console.log('res', res);
});
});
});Finally, register the REST route
//* Add function if not exists
if (!function_exists('handleArchivePosts')) {
function handleArchivePosts(\WP_REST_Request $request): \WP_REST_Response {
//* Get the URL Params
$params = $request->get_query_params();
//* Get our parsed data
$postType = $params['postType'] ?? '';
$postsPerPage = $params['postsPerPage'] ?? 9;
$pageNumber = $params['pageNumber'] ?? 1;
//* Construct WP_Query to get posts
$postsQuery = new \WP_Query([
'post_type' => $postType,
'posts_per_page' => $postsPerPage,
'page' => $pageNumber,
]);
//* Check if we have posts, if not, return error
if (!$postsQuery->have_posts()) {
return new \WP_REST_Response([
'success' => false,
'body' => [
'message' => 'No posts found'
]
], 404);
}
//* We have posts, so return them
return new \WP_REST_Response([
'success' => true,
'body' => [
'posts' => $postsQuery->posts
]
]);
}
}
\add_action('rest_api_ini', function(){
\register_rest_route('SoBold\v1', 'archive/posts', [
'methods' => \WP_REST_Server::READABLE,
'callback' => 'handleArchivePosts',
'permission_callback' => '__return_true'
]);
});