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: