Overwriting images in the content directory

I have a plugin that, when a new CPT post item is created, generates a custom image within its own directory structure. The goal is to get that image into the media library, and to assign it as a featured image of the post that generated it. Straight forward.

As it’s a local image, I’m using wp_upload_bits() (as opposed to a sideload) to copy the file into the content directory… and then using a sequence of wp_insert_attachment(), wp_generate_attachment_metadata(), wp_update_attachment_metadata(), and set_post_thumbnail() to set the image as featured for the given post. This all works. The file is copied into the structure correctly, sliced-n-diced into the theme-declared dimensions, and attached to the post as a featured image. Let’s call this image my-image.jpg for clarity.

Something not quite right…

If I regenerate the image, rather than overwriting my-image.jpg, the system is creating my-image-1.jpg (plus thumbnails) … regenerating the image again creates my-image-2.jpg (and thumbnails) and so on.

I’ve tried wp_delete_attachment() and wp_delete_attachment_files() (one, the other, both, etc), to delete the files (plus thumbnails) before attempting to recreate, but, the files remain on the server and I get a sequential batch of images created.

Does anything here stand out as problematic?

Here is the loose method:

1 Like

That is the standard behavior. There is a function for unique name that you can filter. But changing the main image means the other images should be regenerated also… Does the delete function you used move to Trash? (since an attachment is actually in the post table)

3 Likes

Yes, the thumbs are regenerated based on the new image. …and no, the delete bypasses the Trash by passing true in wp_delete_attachment(). Actually, after posting this issue to Slack, a fellow member pointed out the error. Will update shortly.

1 Like

The block of code responsible for deleting the image is using the parent post ID when it wants the thumbnail ID.

Changing it to this should solve the problem:

    //wp_delete_attachment($plugin_id, true);
    wp_delete_attachment($thumbnail_id, true);
4 Likes

Hi @williampatton - and welcome to the forums. Thanks a lot for so carefully scrutinizing this code in Slack and discovering the error! Appreciate your commenting the solution here. This is resolved.

4 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.