kimil
12/21/2011 - 8:38 AM

WordPress frontend Ajax content loader

WordPress frontend Ajax content loader

/* this assumes you have loaded the relevant http://www.modernizr.com/ compontents */
var sizedetect = function() {

	if (Modernizr.mq("all and (min-width:500px)")) {

		// place an ajax loader
		$(".loadme").html('<div class="ajaxloader"></div>');

		// insert the copy
		if ($(".loadme").length < 30) {
			get_loadme_ajax();
    	        }
	}
}

$(document).ready(sizedetect);
$(window).resize(sizedetect); /* optional - to respond if the browser is resized */
$(document).ready(function() {

	// ajax to fetch the load me data.
	var get_loadme_ajax = function() {
	
		$.ajax({
            type: 'POST',
            url: ajaxurl,
            data: { action: "dhf_loadme_ajax" },
            success: function(data) {
				$('.loadme').html(data);
			}
		});
	};

	$('.showloadme').click( function() { 
		$('.loadme').html('<div class="ajaxloader"></div>');
			get_loadme_ajax();
	});

});
<?php 

/**
 * Enable ajax on the front end
 */
function frontend_ajaxurl() {
?>
<script type="text/javascript">var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';</script>
<?php
}
add_action('wp_head','frontend_ajaxurl');

/**
 * The content we want to show
 */
global $loadme;

$loadme = '
	<section>
		<h1>Who&rsquo;s this guy?</h1>
		<p>I&rsquo;m Tom de Bruin and I make websites.
	</section>
	';

/**
 * Function to call the content
*/
function dhf_loadme_ajax() {
	global $loadme;

	echo $loadme;

	die();
}
add_action('wp_ajax_dhf_loadme_ajax', 'dhf_loadme_ajax' );
add_action('wp_ajax_nopriv_dhf_loadme_ajax', 'dhf_loadme_ajax');

?>
// button to load the content
<a class="button showloadme"><span class="finger">☞</span> Who&rsquo;s this guy?</a>

// css to momentarily display loader image
.ajaxloader { width: 32px; height: 32px; background: url(ajax-loader.gif) no-repeat; margin: auto; }