Updated answer for WordPress 5.5.0+
As of 5.5.0, a new filter has been added to wp_delete_attachment
:
/**
* Filters whether an attachment deletion should take place.
*
* @since 5.5.0
*
* @param bool|null $delete Whether to go forward with deletion.
* @param WP_Post $post Post object.
* @param bool $force_delete Whether to bypass the Trash.
*/
$check = apply_filters( 'pre_delete_attachment', null, $post, $force_delete );
if ( null !== $check ) {
return $check;
}
This "short-circuit" filter is before almost any meaningful action is made, save for trashing the attachment if certain conditions are met. A cleaner approach would now be:
function action_maybe_delete( $id ) {
echo "Let's not delete Attachment id: " . $id ;
// prevent the attachment from actually being deleted
if( 1 == 1 ) { // made up condition
return false;
}
};
// add the action
add_action( 'pre_delete_attachment', 'action_maybe_delete', 10, 1 );
- Returning anything other than
null
from this will preventwp_delete_attachment
from going any further, and instead the result of the filter will be returned.