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.
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.
A little change in the code at ends $imgBeg in place of $imgEnd then it's work fine
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=$imgBeg+1;
}
$more = 0;
}
精彩评论