A plugin for WordPress that allows you to load theme template parts via AJAX.
Sometimes you want to lazy-load content. Installing this plugin provides a new template function:
get_ajax_module( $template, $args );
$template
identifies a template part in your theme named modules/{$template}.php
, and $args
is an associative array of data that you want to be available to that template part when it renders.
Calling this function prints a snippet of JavaScript into your page output each time you call it. It looks something like this:
<script>
(function($, D, W) {
W.__am__ = W.__am__ ? W.__am__ : { c: 0 };
var id = __am__.c++;
D.write('<div id="mod_'+id+'" class="ajax_module_test ajax_module_loading"></div>');
var args = $.extend({ action: 'mod_test', post_id: '286' }, null);
jQuery.post('http://yoursite.com/workbench/wp-admin/admin-ajax.php', args, function(html) {
$('#mod_'+id).removeClass('ajax_module_loading').html(html);
});
})(jQuery, document, window);
</script>
The JavaScript does a couple of things:
-
It creates an empty
div
with classesajax_module_{$template}
andajax_module_loading
. -
It generates an AJAX-request back to your WP site to load the template.
-
It removes the
ajax_module_loading
class from the targetdiv
, and then fills thediv
with the content rendered by the template.
In addition to passing whatever data you supply in $args
, the Post ID of the current global $post
object is also submitted. (You can override this by setting post_id
in $args
.) Your module template can then access this post via $post
.