I explain my problem:

  1. I create a post with an image
  2. get_children - wp_get_attachment_image functions returns that image
  3. I delete post image and add a different one
  4. get_children - wp_get_attachment_image functions returns the two images (although the image that has been removed and is no longer in the post)

The code:

$args = array('post_parent'    => get_the_ID(),
              'post_type'      => 'attachment',
              'post_mime_type' => 'image'
         );

$images = get_children( $args );
if ($images) 
{
    foreach ($images as $image) 
    {
            echo wp_get_attachment_image($image->ID, 'full');
    }
}

You could Limit the output to 1 like this but this is not a solution, only a workaround:

    $args = array('post_parent'    => get_the_ID(),
          'numberposts' => 1, 
          'order'          =>  'ASC',
          'post_type'      => 'attachment',
          'post_mime_type' => 'image'
     );

$images = get_children( $args );
if ($images) 
{
    foreach ($images as $image) 
    {
        echo wp_get_attachment_image($image->ID, 'full');
    }
}

Have you the Premission to delete on your server?

The problem when you update / delete an image from a post or a page, WordPress doesn't change the value of the post_parent column of the attachment. So there is not a 'WordPress' way to exclude the images that are not actually inside the post. At least I haven't found one yet. The query will return all the images that was attached to this post no matter if they were deleted or not.

A solution to this problem is actually to grub the content of the post and search if the url of every image exists inside the post content. I am assuming that you run this script inside WordPress Loop since you are using get_the_ID().

Here is the code for that:

$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');

        }

    }

}

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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