当您从帖子或页面更新/删除图像时,WordPress不会更改post_parent 附件的列。因此,没有一种“WordPress”方法可以排除帖子中实际没有的图像。至少我还没有找到。查询将返回附加到此帖子的所有图像,无论它们是否被删除。
这个问题的一个解决方案实际上是对帖子的内容进行挖掘,并搜索帖子内容中是否存在每个图像的url。我假设您在WordPress循环中运行此脚本,因为您正在使用get_the_ID().
下面是代码:
$args = array(\'post_parent\'    => get_the_ID(),
              \'post_type\'      => \'attachment\',
              \'post_mime_type\' => \'image\'
        );
$images = get_children( $args );
// Store the content of the post
$content = get_the_content();
if ($images){
    foreach ($images as $image) {
        // Get the url of the specific image
        $url = wp_get_attachment_url($image->ID);
        /*
         * Get the position of the url inside the content.
         * If the url does not exist inside content
         * the strpos() returns false.
         */
        $position = strpos($content, $url);
        if ($position){
            echo wp_get_attachment_image($image->ID, \'full\');
        }
    }
}