Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying all images from a WordPress post

I have this piece of code I found on some blog, that's supposed to display all images from a WordPress post.

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 $postOutput; }
        $start=$imgEnd+1;
    }
    $more = 0;
}

What happens though... it displays first and second image correctly, then loops the second image instead of 3rd 4th etc. It grabs the number of images okay, but instead of displaying 1st, 2nd, 3rd, 4th image, it displays 1st, 2nd, 2nd, 2nd...

Could anyone look at this snippet and maybe come up with an idea why this happens? I know the code is rather sloppy, but I just found it on some blog, being a PHP newbie and all :)

All help appreciated, thanks in advance!

like image 286
Justine Avatar asked Nov 02 '10 19:11

Justine


2 Answers

$attachments = get_children(array('post_parent' => $post->ID,
                        'post_status' => 'inherit',
                        'post_type' => 'attachment',
                        'post_mime_type' => 'image',
                        'order' => 'ASC',
                        'orderby' => 'menu_order ID'));

foreach($attachments as $att_id => $attachment) {
    $full_img_url = wp_get_attachment_url($attachment->ID);
    // Your Code here
}

Also you can have a look here: http://www.rlmseo.com/blog/get-images-attached-to-post/

like image 141
Alex Rashkov Avatar answered Sep 23 '22 13:09

Alex Rashkov


its easier now with the new wordpress get_attached_media($type,$post) function

$attachments= get_attached_media( 'image', $post->ID );
foreach($attachments as $att_id => $attachment) {
  $full_img_url = wp_get_attachment_url($attachment->ID);
// You can echo it out here
}

note that this gets only the files uploaded to the post . not files added through media library.

like image 30
Ekene Madunagu Avatar answered Sep 24 '22 13:09

Ekene Madunagu