How to delete post attachments when jQuery is used with a click event on the delete link

I think I’m on the right track with what I need to do, at least for doing one of the ways it could be done. I’m not really sure though, I could be way off for all I know.

This is part of the code I needed help with last night for resizing the uploaded image files, but now I am trying to figure out how to use the wp_delete_attachment($id) function to delete images attached to the posts.

Read More

So, I have this jQuery script that adds/ removes extra fields, for uploading more images to attach. For every added image there is a link to remove them. Clicking remove has only ever just remove the div which the link clicked was contained by, and when saving the post the attached file would show up as still attached.

In my click event handler for the remove link, I need to first run function that will call the wp_delete_attachment(), to permanently delete the file/attachment, THEN I can use jQuery to remove the div of that attachment from the page. That way when saving the post it will have been deleted and not show up again still.

Here’s my functions I’ve been trying to work with:

// a function that returns the delete attachment php function, 
// and a message saying Deleted that fades in and out.
    jQuery(function() {
        function delete_att( attID ) {
            var div = jQuery('#img_uploads'),
                msg = $('div').html('<strong>Attachment Deleted!</strong>').fadeIn().delay(200).fadeOut().appendTo('div');
            return '<?php wp_delete_attachment( ' + attID + ', true ); ?>', msg;
        }

And the click handler which calls this function and then removes the containing div element from the page is:

    jQuery('.remImage').live('click', function() { 
        if( size > 1 ) {
            var postID = jQuery('#attID').val()
            delete_att( postID );

            //jQuery(this).parents('.attchmt').find('#attID');
            jQuery(this).parents('.attchmt').detach();
            size--;
        } 
        return false; 
    });
});

The code to add extra fields is between these two parts but these are the key pieces for what I need help with. Currently, the way I have it coded here I am getting this error message. idk wtf this means exactly though lol.

Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy"  code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)"  location: "http://code.jquery.com/jquery-1.4.4.min.js Line: 113"]

So here is the full code which I am using, exactly. https://gist.github.com/802465
Just trying to pass info to/from jQuery and Php and that’s always a pain in the ass, (for me).

Related posts

Leave a Reply

2 comments

  1. I have finally figured out how to do it, and it now works 100%!!

    Plus it uses the admin-ajax.php so clicking the Remove link there is an ajax request sent to the function that does the deleting of the attachment and returns the message saying it has been deleted.

    Here’s the code for my solution, first is the html for the metabox:

    <a class="remImage" href="#"><?php _e('Remove');?></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' ); ?>" />
    

    Here’s the Php function:

    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;
        }
        die();
    }
    

    And the jQuery script that sends the attachment ID and action, etc., then removes the div from the DOM after receiving the ajax response is:

        jQuery('.remImage').live('click', function() {
            if( size > 1 ) {
                jQuery.ajax({
                    type: 'post',
                    url: ajaxurl,
                    data: {
                        action: 'delete_attachment',
                        att_ID: jQuery(this).parents('.attchmt').find('#att_remove').val(),
                        _ajax_nonce: jQuery('#nonce').val(),
                        post_type: 'attachment'
                    },
                    success: function( html ) {
                        alert( html );
                    }
                });
                jQuery(this).parents('.attchmt').detach();
                size--;
            }
            return false;
        });
    

    I am now able to finally complete what I thought was totally impossible after the number of attempts I’ve made in trying to make it and have failed each time.

    It will soon be a plugin, that I can then use on any site easily, with simple options to define the post type to add it to.

  2. It looks like you are trying to call WordPress function directly form JQuery so that won’t work.
    what you can do is user your function to hide the div but on that action add an hidden field for each attachment you want to remove as an array with the id of the attachment
    something like:

    <input type="hidden" name="att_remove[]" value="attachment_ID">
    

    and then add a function for removing these files at save_post hook
    something like this:

    function remove_custom_att_1212(){
       global $post;
       if ($post->post_type =="your custom post type"){
          if (isset($_POST['att_remove']){
             foreach ($_POST['att_remove'] as $att_id){
               delete_att($att_id);
             }
          }
       }
    }
    add_action('save_post','remove_custom_att_1212');