• Resolved Rob Eschauzier

    (@rob-eschauzier)


    Hey guys and girls,

    I’m writing a plugin to delete duplicate attachments (overwrite uploads didn’t work for me), but I’m having trouble with preserving the file if you delete one of the media attachment dependent on it.

    I’m looking for a hook that get’s called when you remove an attachment. I already found one that works when adding an attachment (wp_handle_upload_prefilter), but no such luck for the deletion of attachments.

    The hooks I have already tried and did not work for my needs:

    before_delete_post
    delete_attachment
    wp_delete_attachment

    Thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    ‘delete_attachment’ works for me. How are you deleting attachments? ‘delete_attachment’ fires from wp_delete_attachment(), which is called from wp-admin/post.php?action=delete, which is the link followed when one picks “delete permanently” from the media library.

    The action passes the attachment ID to your callback, that seems to be all anyone would need.

    Thread Starter Rob Eschauzier

    (@rob-eschauzier)

    Hi,

    Yes I am using wp-admin/post.php?action=delete through the media library menu.

    This is the code I’m using to hook into the action:
    add_action('delete_attachment', array ($this, 'media_overwrite_perserve_attachments'));

    I just found out that if I have a syntax errors in my media_overwrite_perserve_attachments($post_id) function it redirect’s to a blank page. So I guess that the hook is indeed working, it’s my code that’s the problem 😛

    Thanks for pointing me to the correct hook.

    Hi.
    So, i think we need to view a code from

    media_overwrite_perserve_attachments

    . Can you show it?

    Thread Starter Rob Eschauzier

    (@rob-eschauzier)

    It was just some debugging code to display a JS alert box (it previously had a spelling mistake which caused a syntax error):

    MediaOverwriteUtils::displayAlert("deleting file");

    Which calls:

    class MediaOverwriteUtils {
    
    	public static function insertJS($JSContent) {
    
    		return "<script language='javascript'>
    
     					" . $JSContent . "
    
    				</script>";
    	}
    
    	public static function displayAlert($alertContent) {
    
    		echo MediaOverwriteUtils::insertJS("alert('" . $alertContent . "');");
    	}
    }

    It works when called from action hooks that don’t do a page refresh/redirect such as ‘wp_handle_upload_prefilter’, but ‘delete_attachments’ apparently doesn’t execute it (probably due to page refresh).

    I have yet to write any of the actual code for preserving files used by multiple attachments, that’s why marked this issue as resolved.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Hook called when attachment get's removed’ is closed to new replies.