Troy Templeman
Troy Templeman

Reputation: 285

WordPress custom image gallery linking to custom image size

I'm creating a custom image gallery shortcode that opens the images in a lightbox. The line that outputs the images is:

$image_output = "<a href='" . wp_get_attachment_url( $id )  . "' data-toggle='lightbox' data-gallery='$selector' data-footer='$attachment->post_excerpt'> " . wp_get_attachment_image($id, $atts['size'], false, $attr ) . "</a>";

Everything works great except this links to the original (and full size) image. I want it to instead link to a custom image size. I tried wp_get_attachment_url( $id ) with wp_get_attachment_image_src( $id, 'gallery-thumbnail', false ).

However, instead of getting the desired image url I get Array. Any ideas what I'm doing wrong? Should be using something else?

Upvotes: 0

Views: 96

Answers (2)

FluffyKitten
FluffyKitten

Reputation: 14312

wp_get_attachment_image_src takes the post_id and required size as parameters, and returns an array containing:

[0] = url
[1] = width
[2] = height
[3] = is_intermediate (i.e. whether it is a resized image or the original)

Therefore to get the url for a custom size called gallery-thumbnail, you need to do the following:

$img_attrib = wp_get_attachment_image_src( $id, 'gallery-thumbnail');
if ($img_attrib)
    $url = $img_attrib[0];
$image_output = "<a href='".$url."' [...rest of code...] </a>";

I've done it step-by-step so you can see what's happening but you can of course shorten this as follows - however this will have a broken link if the image can't be found.

<a href='".wp_get_attachment_image_src( $id, 'gallery-thumbnail')[0]."' [...rest of code...] </a>"

Note: This assumes you have defined your custom size in functions.php using add_image_size and regenerated your thumbnails so that version of all images has been created.

Ref: Developer Reference for wp_get_attachment_image_src

Upvotes: 1

user8717003
user8717003

Reputation:

wp_get_attachment_image_src() returns an array (url, width, height) so use

wp_get_attachment_image_src(...)[0]

Upvotes: 1

Related Questions