6

I need to modify the_post_thumbnail function to run "Lazyload" on it, i think there is two solutions :

1- modify the args to be something like this

the_post_thumbnail('product', array('data-original'=>$src, 'src'=>'grey.gif'));

(((NOT WORKING!)))

2- get only the image url from the function ... i've tried alot of snippets and nothing worked for me , like this one !

$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "size" );

any ideas??

thanks

3 Answers 3

5

If you want to apply lazyload to each attachment image, you can just add your hoot to wp_get_attachment_image_attributes filter:

add_filter( 'wp_get_attachment_image_attributes', 'wpse8170_add_lazyload_to_attachment_image', 10, 2 );
function wpse8170_add_lazyload_to_attachment_image( $attr, $attachment ) {
    $attr['data-original'] = $attr['src'];
    $attr['src'] = 'grey.gif';
    return $attr;
}

Or if you can use second approach:

$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "size" );
// add more attributes if you need
printf( '<img src="grey.gif" data-original="%s"/>', esc_url( $thumbnail_src[0] ) ); 
4
  • the second approach just like the second solution posted in my post , it just echos "Array"
    – johnmido
    Jun 12, 2012 at 15:43
  • oups... already fixed :) Jun 12, 2012 at 16:04
  • You are the man :)
    – johnmido
    Jun 12, 2012 at 16:17
  • If you please, how to make add_filter apply only on specific registered '$size' s of attachments ?
    – johnmido
    Jun 16, 2012 at 12:55
1

If you dont want to use a hook, in the loop you can do like this:

$loop = new WP_Query( array( 'posts_per_page' => -1 ) );
while ( $loop->have_posts() ) : $loop->the_post(); 

    global $post;
    if ( $image_id = get_post_thumbnail_id( $post->ID ) ){

        if ($src = wp_get_attachment_image_src( $image_id, 'full' )){

                $item.= '<img class="lazy" data-original="' . $src[0] . '"/>';
        }

    }

endwhile; wp_reset_query();
0

Add to your template's functions.php:

function lazyload_image( $html ) {
    $html = str_replace( 'src=', 'data-src=', $html );
    return $html;
}

...

add_filter( 'post_thumbnail_html', 'lazyload_image');

Personally i'm using my own lazyload plugin, unveil.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.