Skip to content

Instantly share code, notes, and snippets.

@deadlyhifi
Created December 21, 2011 08:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save deadlyhifi/1505251 to your computer and use it in GitHub Desktop.
Save deadlyhifi/1505251 to your computer and use it in GitHub Desktop.
WordPress frontend Ajax content loader
// 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; }
<?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');
?>
$(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();
});
});
/* 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 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment