Reload images with different size in WordPress

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

Read More
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();
    });

});

Related posts

Leave a Reply

2 comments

  1. Ok here we go:

    img_get.php:

    <?php
    if (is_file($_GET['img'].'_'.$_GET['size'].'.jpg')) {
       $myImage = imagecreatefromjpeg($_GET['img'].'_'.$_GET['size'].'.jpg');
    } else  {$myImage = imagecreatefromjpeg($_GET['img'].'.jpg');
    header("Content-type: image/jpeg");
    imagejpeg($myImage);
    imagedestroy($myImage);
    ?>
    

    html sample:

    <img class="fixableimg" isrc="common">
    

    js:

    function img_size(Wwidth) {
        if (Wwidth < 800) {
            return("mobile");
        }
        if (Wwidth < 1024) {
            return ("small_1024");
        }
        if (Wwidth < 1280) {
            return ("small_1280");
        }
        //.....
        return ("large_1920");
    
    }
    
        $(window).bind('resize', function() {
            $('.fixableimg').each(function() {
                var obj = $(this);
                var img = obj.attr('isrc');
                var Wwidth = $(window).height();
                obj.attr('src','img_get.php?img='+img+'&size='+img_size(Wwidth));
                });
        });
    

    something like that

  2. @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:

    // your image sizes
    if ( function_exists( 'add_image_size' ) ) { 
        add_image_size( 'mobile', 300, 485 );
        add_image_size( 'small_960', 500, 800 );
        add_image_size( 'medium_1024', 540, 870 );
        add_image_size( 'medium_1280', 670, 1100 );
        add_image_size( 'large_1440', 760, 1230 );
        add_image_size( 'large_1680', 880, 1420 );
    }
    
    // use this to load images inside your loop (with the proper adjustment)
    function image_echo($size, $i_ID) {
        $image_attr = wp_get_attachment_image_src(get_post_thumbnail_id ($i_ID), $size);
    
        ?><img itemprop="image" id="image-atta-<?php echo get_post_thumbnail_id ($i_ID) ?>" 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
    }
    
    // return the resized image
    function resize_ajax_image() {
    
        if(isset($_POST['image_size']) && isset($_POST['attachment_id'])) {
            $image_size = $_POST['image_size'];
            $attachment_id = $_POST['attachment_id'];
    
            $i_attr = wp_get_attachment_image_src($attachment_id, $image_size);
    
            $response = json_encode(array(
                'url' => $i_attr[0],
                'width' => $i_attr[1],
                'height' => $i_attr[2],
            ));
            header("Content-Type: application/json");
            echo $response;
    
            exit;
        }
    
    } add_action( 'wp_ajax_nopriv_resize_ajax_image', 'resize_ajax_image' );
    add_action( 'wp_ajax_resize_ajax_image', 'resize_ajax_image' );
    

    js

    $(document).ready(function() {
    
        function resize_images(size) {
            imageSize = size;
            images = $('img.ajax-resize'); //the image for all resizable images
    
            images.each(function(){
                var this_image = $(this);
                var attachmentID = this_image.attr('attachment-id');
    
                $(this).hide();
    
                $.ajax(
                    theme_info.ajax,{
                        type: 'POST',
                        cache: false,
                        data: {
                            action: 'resize_ajax_image',
                            image_size: imageSize,
                            attachment_id: attachmentID
                        },
                        success: function(image){
                            //console.log(this);
                            this_image.attr({
                                src: image.url, //json object values returned by wordpress
                                height: image.height,
                                width: image.width
                            }).fadeIn(500);
    
                        },
                        error: function(e){
                            console.log(e);
                        }
                    });
            });
        }
    
        var last_image;
        var last_size;
    
        function last_img_fn(keyword) { //do not double resize to the same size
            if (last_image != keyword) {
                last_image = keyword;
                resize_images(keyword);
                //console.log(keyword);
            }
        }
    
        function if_stops_resizing() { //delay 1 second between user starts resizing and when ends. if it corresponds, then resize
            last_size = $(window).height() * $(window).width();
    
            window.setTimeout(function() {
                current_size = $(window).height() * $(window).width();
    
                if (current_size == last_size) {
                    fixImages();
                } else {
                    return false;
                }
            }, 1000);
        }
    
        function fixImages() { //this will depend on how many media queries you do in css or your specific needs
            var winHeight = $(window).height();
            var winWidth = $(window).width();
    
            if (winWidth < 800) {
                //$('body').css('background-color','red');
                last_img_fn('mobile');
    
            }
                if (winWidth < 1024) {
                //$('body').css('background-color','yellow');
                last_img_fn('small_960');
    
            }
                if (winWidth < 1280) {
                //$('body').css('background-color','green');
                last_img_fn('medium_1024');
    
            }
                if (winWidth < 1440) {
                //$('body').css('background-color','white');
                last_img_fn('medium_1280');
    
            }
                if (winWidth < 1680) {
                //$('body').css('background-color','magenta');
                last_img_fn('large_1440');
    
            }
                else { // > 1680
                //$('body').css('background-color','brown');
                last_img_fn('large_1680');
    
            }
        } fixImages(); //fix images on load (not quite sure if the best)
    
    
        $(window).bind('resize', function () {
            var winHeight = $(window).height();
            var winWidth = $(window).width();
    
            last_size = winHeight * winWidth;
            //console.log(last_size);
    
            if_stops_resizing(); //this triggers the whole sequence
        });
    
    });