Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
<img src="spacer.gif" data-src="" class="my-image-class" />
<img src="" />
jQuery(document).ready(function($) {
$('img').each(function() {
// get the image ratio
var ratio = new Image();
ratio.src = $(this).data('src');
var targetEl = $(this),
ajaxData = {
action: 'resize_my_image',
width: $(this).width(),
height: $(this).width() * (ratio.height / ratio.width),
source: $(this).data('src')
$.getJSON(ajaxurl, ajaxData, function(response) {
targetEl.attr('src', response.src);
// include aq resizer script
require_once __DIR__ . '/path/to/aq_resizer.php';
// register the ajax handler
add_action('wp_ajax_resize_my_image', 'resizeImage');
add_action('wp_ajax_nopriv_resize_my_image', 'resizeImage');
function resizeImage()
// explicit declaration of variables
$width = (int) $_GET['width'];
$height = (int) $_GET['height'];
$url = esc_url($_GET['source']);
// call the resize script
$img = aq_resize($url, $width, $height);
// echo the response
echo json_encode(['src' => $img]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.