0

On a single post page, I would like to get the url of the attached images one by one.

For example: I uploaded 5 images in my post from the dashboard. On the single page I want each of their url, like

<div style="background-image: url('<?php first-attachment-url ?>')"></div>
<div style="background-image: url('<?php second-attachment-url ?>')"></div>
<div style="background-image: url('<?php third-attachment-url ?>')"></div>
<div style="background-image: url('<?php fourth-attachment-url ?>')"></div>
<div style="background-image: url('<?php fifth-attachment-url ?>')"></div>

I also need to loop through them because I want it to work regardless of the amount of the images, e.g. if I upload 2, or 10 images it should work in both cases

How can I do that?

2

Put this in the template file at the beginning or in functions.php file:

function get_images_attachment_url()
{
  global $post; 
  $images_urls = array();

  $images_objects = get_attached_media( 'image', $post->ID );

  foreach ($images_objects as $image_object) {
    $images_urls[] = wp_get_attachment_url ($image_object->ID);
  } 
  return $images_urls;
}

When you need to call them use foreach after calling the function get_images_attachment_url():

$my_images_urls = get_images_attachment_url();
foreach ($my_images_urls as $url) {
?>
  <div style="background-image: url('<?php echo $url  ?>')"></div>
<?php
}
  • Unfortunately it spits out Undefined variable for images_urls, as well as images_objects. Any idea whats the matter? edit: It had a few typos, but managed to fix it, didn't see them at first – lastnoob Jul 3 '17 at 22:27
  • I fixed my script I forget to add the $ at my_images_urls and fixed $image_objects->ID to $image_object->ID, Now I fixed it. Copy it and try now, It should work – Salvio Jul 3 '17 at 22:33
  • it shows the same image (the featured one) on every div – lastnoob Jul 3 '17 at 22:49
  • Sorry fo the late. I fixed my code and tested it, now it works... – Salvio Jul 4 '17 at 14:59

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.