Need to get all <img> from the_content(); in wordpress?

I’ve recently just imported all of the content from a blogger site into wordpress and I need to tidy things up a bit.

I’m working inside the single.php and I want to get each <a><img src=""/></a> from the_content();. My php is a little shoddy at best.

Read More

I understand this gets me the first image of the post, but I need something similar, one that gets me all the images (not featured images) from the_content();.

function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
    $first_img = $matches[1][0];

    if(empty($first_img)) {
        $first_img = "/path/to/default.png";
    }
    return $first_img;
} 

Related posts

Leave a Reply

2 comments

  1. Trivial task for DOMDocument:

    $doc = new DOMDocument();
    $doc->loadHTML($post->post_content);
    foreach ($doc->getElementsByTagName('img') as $img)
        $img->attributes['src'] = '/path/to/default.png'; // or whatever you want to do
    return $doc->saveHTML();
    

    You need to watch out though, saveHTML() might add missing tags around your structure.