Get images used in, but not attached to page?

I want to get all of the images used in a page. This is the code I’m using:

function get_page_images($id) {
    $photos = get_children( array(
        'post_parent' => $id,
        'post_status' => 'inherit',
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'order' => 'ASC',
        'orderby' => 'menu_order ID') );

    $results = array();

    if ($photos) {
        foreach ($photos as $photo) {
            // get the correct image html for the selected size
            $results[] = wp_get_attachment_image($photo->ID, $size);
        }
    }

    return $results;
}

This only gets images uploaded specifically for this page, if I have reused an image that was already previously uploaded for a different page/post, those aren’t retrieved (as they are attached to the post they were uploaded to, but not any posts they are reused in). Does anyone know a way to get all the images used in a page/post?

Related posts

Leave a Reply

2 comments

  1. Use the built-in PHP Dom Parser to grab all images located in your content. This code is untested, but should get you started in the right direction:

    <?php
    while(have_posts()) : the_post();
        $dom = new DOMDocument();
        $dom->loadHTML(get_the_content());
        $images = $dom->getElementsByTagName('img');
        foreach($images as $img){
            $src = $img->getAttribute('src');
            printf('<img src="%s" />', $src);
        }
    endwhile;
    ?>
    
  2. I think follwoing function will usefull for get images from post

    function get_images_from_post( $id ) {
       $get_custom_post = get_post($id); 
       $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $get_custom_post->post_content, $matches);
       return $matches;
    }