tags:

views:

24

answers:

1

I'm trying to get all images from a WP post to create a slideshow from them. Googled around and found this piece of code to retrieve and display images from a post:

function getImage($num) {
    global $more;
    $more = 1;
    $link = get_permalink();
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;
    for($i=1;$i<=$count;$i++) {
        $imgBeg = strpos($content, '<img', $start);
        $post = substr($content, $imgBeg);
        $imgEnd = strpos($post, '>');
        $postOutput = substr($post, 0, $imgEnd+1);
        $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
        $image[$i] = $postOutput;
        $start=$imgEnd+1;
    }
    if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
    $more = 0;
}

As you can imagine you then use getImage('1') etc. to get 1st, 2nd images from the post etc. This isn't ideal to create a slideshow, because I don't know how many image will there be.

Is there a way to modify the code above to get an array of images to use to create a foreach loop, for example? Sorry if my logic is a bit flawed, I'm not a PHP expert, as you might have guessed.

Thanks in advance for any help.

+1  A: 

This code is already finding all the images, but is only printing out 1.

Try this variation, which should echo all images instead of just 1. I haven't tested this, but if you original code worked, this should.

function getImage() {
    global $more;
    $more = 1;
    $link = get_permalink();
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;
    for($i=1;$i<=$count;$i++) {
        $imgBeg = strpos($content, '<img', $start);
        $post = substr($content, $imgBeg);
        $imgEnd = strpos($post, '>');
        $postOutput = substr($post, 0, $imgEnd+1);
        $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
        if(stristr($postOutput,'<img')) { echo '<a href="'.$link.'">'.$postOutput."</a>"; }
        $start=$imgEnd+1;
    }
    $more = 0;
}

There is a lot more cleanup that could be done on this code as well, but I just modified what you had.

Alan Geleynse
That did the trick, thank you. Like I said, I grabbed this snippet from some blog. If there's something that could be cleaned up, I'm always willing to learn if you can explain :)
Justine
One question: what does this function return? Is it an array or just a bunch of code? I wanted to create a foreach statement using these images but doesn't seem like I'm able to.
Justine
This code just echos out all your images, it does not return them. The for loop within this code is already looping over all the images. If you comment out the `if` line, you can turn off the echoing and put your own code within the loop. Or you can change it to put each `$postOutput` into an array and return that array which you can then loop over.
Alan Geleynse