delete attachment from front end

All we need is an easy explanation of the problem, so here it is.

logged in as admin and trying to code that deletes posts to delete an attachment.


<?php if (current_user_can('edit_post', $attachment->ID)) 
echo "<a href='" . wp_nonce_url("/wp-admin/post.php?action=delete&amp;post=".$attachment->ID."", 'delete-post_' . $attachment->ID) . "'>Delete</a>" ?>

but it just takes me to a page that says;

Are you sure you want to do this?
Please try again.

and the please try again links back to the post…

is it something to do with the delete-post_

best, dan.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

ended up using ajax in the end…


<a class="remImage" name="<?php echo $attachment->ID; ?>" href="#" rel="nofollow noreferrer noopener"><?php _e('delete');?></a>  <input type="hidden" id="att_remove" name="att_remove[]" value="<?php echo $attachment->ID; ?>" />
<input type="hidden" name="nonce" id="nonce" value="<?php echo wp_create_nonce( 'delete_attachment' ); ?>" />


$('.remImage').live('click', function() {
    var attID = jQuery(this).attr('name');
        type: 'post',
        url: '/wp-admin/admin-ajax.php',
        data: {
            action: 'delete_attachment',
            att_ID: jQuery(this).attr('name'),
            _ajax_nonce: jQuery('#nonce').val(),
            post_type: 'attachment'
        success: function() {

in functions.php

add_action( 'wp_ajax_delete_attachment', 'delete_attachment' );
function delete_attachment( $post ) {
    //echo $_POST['att_ID'];
    $msg = 'Attachment ID [' . $_POST['att_ID'] . '] has been deleted!';
    if( wp_delete_attachment( $_POST['att_ID'], true )) {
        echo $msg;

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply