0

I am trying to retrieve just the urls, not the whole image objects, from a gallery. I am stuck, because I can either get only the full size of images via:

wp_get_attachment_url

because this doesn't accept any parameters, or get the whole img tag with all kinds of stuff via:

wp_get_attachment_image

Is there a way to get the urls? My code right now looks like this:

<?php
    $query_images_args = array(
                               'post_type' => 'attachment',
                               'post_mime_type' => 'image',
                               'post_status' => 'inherit',
                               'posts_per_page' => -1,);

    $query_images = new WP_Query( $query_images_args );

    class image {
        public $thumbnail_url;
        public $full_url;
    }
    $images = array();
    foreach ( $query_images->posts as $picture ) {
        $image = new image();
        $image->thumbnail_url = wp_get_attachment_image( $picture->ID, 'thumbnail' );
        $image->full_url = wp_get_attachment_image( $picture->ID, 'full' );
        array_push($images, $image);
    }

    foreach($images as $image) {
        $thumbnail_url = $image->thumbnail_url;
        $full_url = $image->full_url;
?>

I want to be able to fill this correctly:

<li><img data-full-url="<?php echo $full_url ?>" src="<?php echo $thumbnail_url; ?>" /></li>
1

I don't understand your code in full (how your foreach's actually fill your list item), but, as for the specific question, I think that the function you want is wp_get_attachment_image_src();

So (illustratively):

   $thumbnail_src = wp_get_attachment_image_src( $picture->ID );
   $image->thumbnail_url = $thumbnail_src[0];
   $full_src = wp_get_attachment_image_src( $picture->ID, 'full' );
   $image->full_url = $full_src[0];
  • Sweet, it worked. How didn't I find this function. Thank you! – Frederik Witte Jul 18 '16 at 8:43
  • Btw just one thing, you can also just use: $image->thumbnail_url = wp_get_attachment_image_src( $picture->ID )[0]; in one line – Frederik Witte Jul 18 '16 at 12:30
  • I believe you can, though it will fail in some older WordPress configurations. – CK MacLeod Jul 18 '16 at 14:49

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.