wp-ajax-modules

Created: 2011-07-15 01:24
Updated: 2014-02-28 11:04
php

README.mkd

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:

  1. It creates an empty div with classes ajax_module_{$template} and ajax_module_loading.

  2. It generates an AJAX-request back to your WP site to load the template.

  3. It removes the ajax_module_loading class from the target div, and then fills the div 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.

Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more