0

i want to get a post embedded images but the only methods i see over the internet are

        $attachments = get_posts(array(
            'post_parent'       => get_the_ID(),
            'post_type'         => 'attachment',
            'posts_per_page'    => $n,
            'post_mime_type' => 'image'
        ));


        $attachments = get_children(array(
            'post_parent'       => get_the_ID(),
            'post_type'         => 'attachment',
            'posts_per_page'    => $n,
            'post_mime_type' => 'image'
        ));

        $attachments = get_attached_media('image', get_the_ID());

but this gives only the attached images i want all the images in a post even if they are not attached to that post 'post_parent' => get_the_ID()

i think this is the wordpress way of attaching images it sounds like a one-to-many relationship an image can only be attached to one post

any idea ? thanks in advance

1
  • If you mean all embedded images from post content, maybe you can try a regex in post content to search all images. Also you should look for all post meta in a same way. But if any post meta has attachment ID instead of URL, it can be quite impossible unless you explicitly know which meta key contains an attachment ID. Mar 11 at 17:55
0

You can use DOMDocument to get every image from any page:

function testingdom(){

    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    
    $dom->loadHTMLFile('https://the_post_url.com/anyone');
    $data = $dom->getElementsByTagName("img");
    
    $srcs = array();
    foreach($data as $key => $dat){
        $srcs[] =  $data->item($key)->getAttribute("src");
    }
    
    $dom = null;

}
add_action("wp_head", "testingdom");

This way you should have every src in an array called srcs

2
  • yeah this might work and you can also select them via some regex i'm just wondring if there is a wordpress function that could do the job Mar 11 at 20:19
  • Dont think so, maybe you can create a function to get_post / post_content and look for every src Mar 11 at 20:23
0

i think if WordPress doesn't provide such a function then this is the shortest way

function my_get_embeded_media() {
    $content = apply_filters('the_content', get_the_content());

    $arr = preg_match_all("/<img[^>]* src=\"([^\"]*)\"[^>]*>/", $content, $matches);

    return $arr ? $matches[1] : array();
}

but we still can't control the images size!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.