Modify WordPress get_image_tag output?

According to jQuery.lazyload any images I’d like to “lazyload” need to have the src attribute replaced with data-original.

I’m assuming I can do this using WordPress get_image_tag filter, but I’m stuck on how to actually make it happen.

Read More
function image_src( $id, $alt, $title, $align, $size ) {
    $html = '<img data-orginial="' . esc_attr($img_src) . '"/>';
    return $html;
}
add_filter( 'get_image_tag', 'image_src', 10, 5 );

For lazyload to work a lazy class also needs to be placed on the IMG, which I managed to get working using WordPress get_image_tag_class filter

function image_class( $classes ) {
    return $classes . ' lazy';
}
add_filter( 'get_image_tag_class', 'image_class' );

Any thoughts on how I can change the IMG output to replace data-orginial instead of src?

Related posts

Leave a Reply

2 comments

  1. Rich-

    I ran into the same problem and went down the same path as you, trying to use get_image_tag with poor results. So I came up with a JS workaround – the code comments should show you how to get this working:

    function() {
      // To get lazy loading working on blog post
      // 1- Assign all image source paths into a sourcePath variable
      var sourcePath = $("figure").find("img").attr("src");
    
      // 2- Nullify source paths, move path to data-original attribute and add lazy-load class to img
      $("figure").find("img").attr({
        "src" : " ",
        "data-original" : sourcePath
      }).addClass("lazy-load");
    
      // 3- Applies lazy-loading jQuery plugin to image elements
      $("img.lazy-load").lazyload({
        effect : "fadeIn"
      });
    }
    
  2. You will need to replace the src part

    function image_src( $id, $alt, $title, $align, $size ) {
      if( ! is_admin() ) $html = str_replace("img src=","img data-original=",$html);
      return $html;
    }
    add_filter( 'get_image_tag', 'image_src', 10, 5 );
    

    You may have to adjust it to make it match the original <img> settings.

    Edit: added Nath’s suggestion.