I wrote some jquery/php to reload images in my wordpress theme on the window resize. It loads random code and then crashes. Any ideas are welcome.
Thank you.
PHP
function head_scripts() {
if ( !is_admin() ) {
wp_localize_script( 'init', 'theme_info', array( 'ajax' => admin_url( 'admin-ajax.php' ) ) );
}
} add_action('init', 'head_scripts');
function image_echo($size, $i_ID) {
$image_attr = wp_get_attachment_image_src(get_post_thumbnail_id($i_ID), $size);
?><img itemprop="image" class="ajax-resize" attachment-id="<?php echo get_post_thumbnail_id ($i_ID) ?>" src="<?php echo $image_attr[0]; ?>" width="<?php echo $image_attr[1]; ?>" height="<?php echo $image_attr[2]; ?>" alt="<?php echo get_the_title($i_ID); ?>"/><?php
}
function resize_ajax_image() {
if(isset($_POST['image_size'])) {
$image_size = $_POST['image_size'];
}
if(isset($_POST['attachment_id'])) {
$attachment_id = $_POST['attachment_id'];
}
image_echo($image_size, $attachment_id);
die();
} add_action( 'wp_ajax_nopriv_resize_ajax_image', 'resize_ajax_image' );
add_action( 'wp_ajax_resize_ajax_image', 'resize_ajax_image' );
jQuery
$(document).ready(function() {
function find_ajax_images(imageSize) {
$('.ajax-resize').each(function(){
var attachmentID = parseInt($(this).attr('attachment-id'));
$.ajax(
theme_info.ajax,{
type: 'POST',
cache: false,
data: {
action: 'resize_ajax_image',
image_size: imageSize,
attachment_id: attachmentID
},
success: function(resizeImage){
$(this).html(resizeImage);
}
});
});
}
function fixImages() {
var winHeight = $(window).height();
var winWidth = $(window).width();
if (winWidth < 800) {
//$('body').css('background-color','red');
find_ajax_images('mobile');
} else if (winWidth < 1024) {
//$('body').css('background-color','yellow');
find_ajax_images('small_1024');
} else if (winWidth < 1280) {
//$('body').css('background-color','green');
find_ajax_images('medium_1280');
} else if (winWidth < 1440) {
//$('body').css('background-color','white');
find_ajax_images('medium_1440');
} else if (winWidth < 1680) {
//$('body').css('background-color','magenta');
find_ajax_images('large_1680');
} else { // > 1680
//$('body').css('background-color','brown');
find_ajax_images('large_1920');
} //nested if
}
$(window).bind('resize', function () {
fixImages();
});
});
Ok here we go:
img_get.php:
html sample:
js:
something like that
@eicto ‘s solution was the optimal, but it doesn’t really integrates with the way WordPress works with images (media library). So yes, in the end I did some ajax with jQuery.
First, localize your ajax, then:
js