12

Hi I'm using some code to create a slideshow with lytebox functionality - the following code is used in the loop to pull each image attached to a post in sequence.

It seems to be only pulling the large image, even thought I've set the value to medium - any ideas how I can get .wp_get_attachment_url($attachment->ID, 'medium', false, false) to be pulling the medium sized images?

thanks

                                <?php
$argsThumb = array(
'order'          => 'DESC',
'post_type'      => 'attachment',
'post_parent'    => $post->ID,
'post_mime_type' => 'image',
'post_status'    => null
);
$attachments = get_posts($argsThumb);
if ($attachments) {
foreach ($attachments as $attachment) {
echo '<div class="images"><a class="lytebox" href="' .wp_get_attachment_url($attachment->ID, 'medium', false, false). '"><img src="'.wp_get_attachment_url($attachment->ID, 'medium', false, false).'" /><div class="caption">'.apply_filters('the_content', $attachment->post_content).'</div></a></div>';
}

}

25

wp_get_attachment_url() will only return url to original attachment file, this function only accepts attachment id as parameter.

Use wp_get_attachment_image_src() or wp_get_attachment_image() instead.

3
  • 1
    neither of those seem to return the url though do they? Mar 12 '12 at 16:55
  • 1
    wp_get_attachment_src() returns array and first parameter is image url. See linked codex page for more details.
    – Mamaduka
    Mar 12 '12 at 17:01
  • 3
    Update for those finding this all these years later. The function you want is called wp_get_attachment_image_url(). All you need to do is give it the attachment ID and the size and it will return either a string of the image url or false. Oct 17 '20 at 4:22
12

echo out the following: wp_get_attachment_image_src( $post->ID, 'medium')[0]; to the attachment url for the medium sized image.

2
  • 3
    Function array dereferencing is a PHP 5.4+ feature. Not that this should be a problem. Just to let anyone know.
    – tfrommen
    Aug 19 '15 at 19:25
  • Update for those finding this all these years later. The function you want is called wp_get_attachment_image_url(). All you need to do is give it the attachment ID and the size and it will return either a string of the image url or false. Oct 23 '20 at 21:32
2

Update for those finding this all these years later. The function you want is called wp_get_attachment_image_url(). Documentation here.

All you need to do is give it the attachment ID and the size and it will return either a string of the image url or false.

1

I don't how above answer makes the answer. wp_get_attachment_image_src need attachment id not post id. <?php echo esc_url((wp_get_attachment_image_src( get_post_thumbnail_id(get_the_id()), 'medium')[0])?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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