• I have given permission to the users to register on my blog and add the contents (posts). User can attach max 3 images to a single post.

    Problem: A user uploads multiple images (say 20 images) to media library, then he finalizes 3 images from media library to attach with the post. So uncesserarily 17 images still are in media library which are unattached.

    Seeking solution for: So I require a function/filter to clear the unattached images (remaining 17 images), which I can run on Submit post action in function.php.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    First let’s be sure we are using the same vocabulary. You wish to remove unattached images, I know what you mean, but if the images were uploaded with the media manager, there remains attachment records even though they are not actually inserted in the post. Thus in a sense they are still attached, though not inserted.

    There are complicating factors which may or may not apply. If an image was inserted from the library, an image initially uploaded for an earlier post and reused again, it is inserted, but no attachment record exists related to the new post, only the old post. Shouldn’t matter here, but something you will want to be aware of in general.

    I think what you want to do when the post is submitted is search through the content and compile an array list of all image IDs inserted in the content. Each img tag should have a class name of the form “wp_image_{$image_id}” which you could use to build the array.

    Also check the post meta for any featured images, you do not want to accidentally delete that just because it is not in the content.

    Then query for all attachments to the post, excluding those that are inserted in the post or are featured. Unlink (PHP for delete) all image files associated with the attachments. Remember there can be several images of different sizes for each attachment.

    Once all the files are unlinked, you can delete all the associated attachment records.

Viewing 1 replies (of 1 total)
  • The topic ‘delete unattached images on post submit’ is closed to new replies.