获取使用但未附加到页面的图像?

Mat*_*ain 1 wordpress

我想获得页面中使用的所有图像.这是我正在使用的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

这只会获取专门为此页面上传的图片,如果我重新使用之前已经上传过的图片用于不同的页面/帖子,则不会检索这些图片(因为它们附加到他们上传到的帖子,但不是任何帖子它们被重复使用).有没有人知道如何获取页面/帖子中使用的所有图像?

mai*_*o84 5

使用内置的PHP Dom Parser获取内容中的所有图像.此代码未经测试,但应该让您从正确的方向开始:

<?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;
?>
Run Code Online (Sandbox Code Playgroud)