get_attached_media() returns empty array if media file already used by another post

I ran into this problem and ended up creating a basic function to extract the “attached” media by URL from the body of the post (in my case a post of type document, but it should work with any kind of post):

function get_first_link_url($post_id) {
    $content = get_post_field('post_content', $post_id);
    if ($content == null) {
        return null;
    }
    $dom = new DOMDocument();
    $dom->loadHTML($content);
    $links = $dom->getElementsByTagName("a");
    if (count($links) == 0) {
        return null;
    }
    $url = $links[0]->getAttribute('href');
    return $url;
}

This only returns the URL (href) of the first tag in the post, but it could readily be modified to return all of them as an array.

Leave a Comment