The REST API extension for Ajax Load More will enable compatibility between Ajax Load More and the WordPress REST API.
Easily access your website data (as JSON) through an HTTP REST API and display the results using infinite scroll with Ajax Load More.
How It Works
The REST API extension works by routing the standard Ajax Load More admin-ajax.php requests to API endpoints for data retrieval. The data is returned as JSON, then parsed and displayed using Underscore.js styled templates on the front-end of your website.
Using a simple GET request, a JavaScript Repeater Template and custom endpoint (/wp-json/ajaxloadmore/posts) developed specifically for Ajax Load More users are able to access website data and infinite scroll the results using the WP REST API.
WordPress 4.7+ or the WP REST API v2 must be installed and activated for use with this extension.
REST API Endpoints
The REST API extension comes pre-packaged with a /posts custom endpoint developed to integrate seamlessly with all currently available Ajax Load More Shortcode Parameters – this means you can build your Ajax Load More query as usual and the custom /posts endpoint will handle the display for you without the need for any endpoint development.
Custom Endpoints
Custom REST API endpoints will provide Ajax Load More users the ability to create custom database queries and modify the data returned from these queries without being confined to a set of Shortcode Parameters.
Endpoints can be added for use with Ajax Load More and other applications by simply adding the routes and endpoints directly to the functions.php file in your current theme directory. Once endpoints have been added to your theme, you can go ahead instruct Ajax Load More to start referencing them by updating the restapi_base, restapi_namespace and restapi_endpoint in your shortcode.
Example Endpoint
The following example of a custom route and endpoint will simply grab the latest portfolio custom post type and order the return data by date, desc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<?php /* * Custom WP REST API Routes * http://v2.wp-api.org/extending/adding/ */ add_action( 'rest_api_init', function () { $my_namespace = 'my_custom_namespace'; $my_endpoint = '/posts'; register_rest_route( $my_namespace, $my_endpoint, array( 'methods' => 'GET', 'callback' => 'my_get_posts_function', )); }); /* * Custom /posts endpoint for my_custom_namespace * * [ajax_load_more restapi="true" restapi_base="/wp-json" restapi_namespace="my_custom_namespace" restapi_endpoint="my_get_posts_function"] * * @param array $data Options for the function. * @return json object of post data. */ function my_get_posts_function( $data ) { $response = array(); /* Defaults */ $page = $data['page']; // get the current page from ALM [** REQUIRED **] $posts_per_page = !empty($data['posts_per_page']) ? $data['posts_per_page'] : 5; // get the posts_per_page from ALM /* Query Arguments */ $args = array( 'posts_per_page' => $posts_per_page, // REQUIRED 'offset' => $data['offset'] + $page * $posts_per_page, // REQUIRED 'post_type' => 'portfolio', 'orderby' => 'date', 'order' => 'DESC', 'post_status' => 'publish', ); /* Run WP_Query() */ $posts = new WP_Query( $args ); // Create ALM Template Vars [https://connekthq.com/plugins/ajax-load-more/docs/variables/] $alm_item = $page * $posts_per_page; $alm_found_posts = $posts->found_posts; $alm_current = 0; while ( $posts->have_posts() ) : $posts->the_post(); $alm_current++; // Get post thumbnail $thumbnail_id = get_post_thumbnail_id(); $thumbnail = ''; if($thumbnail_id){ $thumbnail_arr = wp_get_attachment_image_src($thumbnail_id, 'alm-thumbnail', true); $thumbnail = $thumbnail_arr[0]; } // Build $data JSON object $data = array( 'alm_page' => $page + 1, 'alm_item' => ($alm_item++) + 1, 'alm_current' => $alm_current, 'alm_found_posts' => $alm_found_posts, 'date' => get_the_time("F d, Y"), 'link' => get_permalink(), 'post_title' => get_the_title(), 'thumbnail' => $thumbnail, ); $content = get_the_content(); // Content $data['post_content'] = apply_filters('the_content', get_the_content()); // add 'post_content' to returned json $response[] = $data; endwhile; wp_reset_query(); if (empty($response)) return null; return $response; // Return data } |
NOTE: It’s important to always keep the $page and $posts_per_page parameters when developing a custom endpoint – these are required for Ajax Load More to correctly offset each database query.
Templates
Repeater Templates created for use with Ajax Load More and the REST API extension are required to be developed using wp.template, which is a JavaScript templating syntax very similar to Underscore.js.
The REST API extension requires templates to be written in JavaScript as the data returned from API requests will be parsed and displayed on the client side, where standard Ajax Load More admin-ajax.php requests are parsed on the server and returned to the client as HTML for display.
Wrapping Templates
JavaScript templates are always defined between a script block with a type=’text/html’ and must also contain a unique id (tmpl-[template-name]) for referencing the correct template in the DOM.
1 2 3 |
<script type="text/html" id="tmpl-alm-template"> <!-- Your JavaScript template goes here --> </script> |
Example JavaScript (Repeater) Template
The following example transforms the default Ajax Load More PHP/HTML based template into a JavaScript template – this template will be repeated for each result returned from the API endpoint.
1 2 3 4 5 6 7 8 9 10 |
<script type="text/html" id="tmpl-alm-template"> <li <# if(!data.thumbnail){ #> class="no-img" <# } #>> <# if(data.thumbnail){ #> <a href="{{{data.link}}}"><img src="{{{data.thumbnail}}}" alt="{{{data.thumbnail_alt}}}" /></a> <# } #> <h3><a href="{{{data.link}}}">{{{ data.post_title }}}</a></h1></h3> <p class="entry-meta">{{{ data.date }}}</p> <p>{{{ data.post_excerpt }}}</p> </li> </script> |
You will notice that the only real differences between standard PHP based templates and a JavaScript templates are the opening and closing script block and the {{ data.var }} template tags, which is a WordPress-specific interpolation syntax that’s heavily inspired by Mustache templating.
Before you start templating you’ll want to get familiar with the following templates tags:
- {{ data.var }} – used for escaped data.
- {{{ data.var }}} – used for raw data (not escaped).
- <# if() #> – evaluate any JavaScript code.
NOTE: As seen in the example above, all data returned by the REST API extension will be accessed in your templates via the data variable. e.g. {{{ data.post_title }}}
Need Some More Help?
We’ve compiled a list of resources for further reading on developing with wp.template:
- Official WordPress Codex for wp.template
- wp.template for front end templating in WordPress – by Luke Woodward
- Intro to Underscore.js templates in WordPress – by Justin Tadlock
- WordPress underscore template – by Jose M Castaneda
Shortcode Parameters
Use the following shortcode parameters to initiate the REST API and Ajax Load More.
restapi | Enable the WordPress REST API. (true/false) Default = ‘false’ |
---|---|
restapi_base | The base URL to your installation of the REST API. Default = ‘/wp-json’ |
restapi_namespace | Enter the custom namespace for this Ajax Load More query. Default = ‘ajaxloadmore’ |
restapi_endpoint | Enter your custom endpoint for this Ajax Load More query. Default = ‘posts’ |
restapi_template_id | Enter the ID of your javascript template. |
restapi_debug | Enable debugging (console.log) of REST API responses in the browser console. Default = ‘false’ |
Shortcode Builder
The following screenshot illustrates the process of building a REST API shortcode using the Ajax Load More shortcode builder.
Note: Ajax Load More references restapi_template_id while looping and displaying data. You must still select a repeater template for each instance of Ajax Load More.
Example Shortcode
[ajax_load_more repeater="template_5" restapi="true" restapi_base="/wp-json" restapi_namespace="ajaxloadmore" restapi_endpoint="posts" restapi_template_id="alm-template" restapi_debug="true" post_type="post"]
Frequently Asked Questions
Below are common questions regarding the REST API extension. If you have a question and don’t see an answer here, please visit the support page and submit your request.
Namespaces are the first part of the URL for the endpoint. Namespaces allows for two plugins to add a route of the same name, with different functionality.
Need more info? Read the official documentation on Namespacing.
You should add your custom endpoints to the functions.php file in your current theme directory.
No, all Repeater Templates that are used with the REST API extension must be coded as a JavaScript template.
Yes! As long as you are using the default /wp-json/ajaxloadmore/posts endpoint all values passed via shortcode will be parsed in your API call.
Yes, the alm_restapi_url can be used to filter the site URL for the Rest API call.
1 2 3 |
add_filter( 'alm_restapi_url', function(){ return 'https://blog.website.com'; }); |