I am having an overview of custom post types. These have custom tax and also an attachment.
In my overview I need to provide links to delete the entries. With that I also need to delete the attachment and the meta data.
I was using this:
if ( !current_user_can( 'delete_bkroadkill', $post->ID ) )
return;
$link = "<a href='" . wp_nonce_url( get_bloginfo('url') . "/wp-admin/post.php?action=delete&post=" . $post->ID, 'delete-post_' . $post->ID) . "'>".$link."</a>";
echo $before . $link . $after;
I found Delete Post Link to delete post, its meta and attachments but there is no solution provided.
Which will not delete anything else than the post. What is the proper way to do this?
@s_ha_dum suggests that Post meta will be deleted automatically. Therefore because his reputation suggests he knows what he is talking about, this solution only handles Post attachments.
I’d suggest checking out the docs for the before_delete_post() hook, as it’s quite handy to be able to check out what Post Type is being deleted, etc.
An important note from the aforementioned docs –
It’s important to note the hook runs only when the WordPress user empties the Trash. If you using this hook note that it will not fire if the user is deleting an Attachment, since attachments are force deleted, i.e., not sent to the Trash. Instead use the delete_post() hook.
Another note
I should mention that while the code in this answer will delete all rows from the database related to Post attachments, it will not actually delete the attachments themselves.
My reasoning for this is performance. Depending on the number of attachments that you have, deleting them one at a time could take a while. I suggest it is better to to only delete the database entries for all attachments initially to enhance the user experience, and then run some separate house keeping at another time to delete the actual attachments (it’s easy enough to search for and delete and non-associated files). Basically, less queries + less work during the user experience = less time.
I use this to delete associated media with post. If you want to test against a certain post type you can include the
global $post_type
variable. Pretty much it gets all attachments and deletes them one by one. Reference