Custom image size not displaying with wp_get_attachment_image()
-
I created a custom image size for my portfolio thumbnails
add_image_size( 'gallery-thumb', 240, 180, true );
I created a shortcode to display all images using a lightbox with lazy loading to generate the following HTML:
<a href="/wp-content/uploads/mobile-responsive-website.png" data-lightbox="gallery" title=""> <img width="240" height="180" src="" class="image_zoom" alt="" loading="lazy" data-src="/wp-content/uploads/mobile-responsive-website-240x180.png"> </a>
1. The href needs to be the full size image
2. The image custom size image (gallery-thumb) needs to load into data-src for lazy loading (with no src)For the image, I used
wp_get_attachment_image()
$image = wp_get_attachment_image( $attachment_id, 'gallery-thumb', false, array( 'class' => 'lazy image_zoom', 'data-src' => $url, 'src' => '') );
BUT, this doesn’t work, the image is loading the full size, not the custom size (see below). I have checked the URL and the custom size exists… Is there a problem with
wp_get_attachment_image()
and custom sizes?<img width="240" height="180" src="" class="lazy image_zoom" alt="" loading="lazy" data-src="/wp-content/uploads/mobile-responsive-website.png">
The size it is loading is the full size with the correct width and height settings (so it is scaling the image) – How do I force it to load the cropped custom image size?
Full Shortcode:
function add_gallery($attr) { $output = ''; if ( !empty( $attr["ids"] ) ) { $ids = explode(",", $attr["ids"]); } if( isset($ids) ) { $output .= '<div class="row gallery">'; foreach( $ids as $attachment_id ) { $url = wp_get_attachment_image_url( $attachment_id, 'full', false); $image = wp_get_attachment_image( $attachment_id, 'gallery-thumb', false, array( 'class' => 'lazy image_zoom', 'data-src' => $url, 'src' => '') ); $alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true); if ( !empty($image) ) { $output .= '<div class="col grid_4_of_12">'; $output .= ' <a href="'.$url.'" '; $output .= ' data-lightbox="gallery" title="'.$alt.'">'; $output .= $image; $output .= ' </a>'; $output .= '</div>'; } } $output .= '</div>'; } return $output; } add_shortcode('my_gallery','add_gallery');
- The topic ‘Custom image size not displaying with wp_get_attachment_image()’ is closed to new replies.