Delete attachments from Front end

You can do it via ajax, first, let’s change your current function to this:

<?php 

$args = array(
    'order'          => 'ASC',
            'orderby'        => 'menu_order',
            'post_type'      => 'attachment',
            'post_parent'    => $post->ID,
            'post_mime_type' => 'image',
            'post_status'    => null,
            'numberposts'    => -1,
    );          

$images = get_posts( $args );
$imagenum=0;
foreach($images as $image):
    $imagenum++;
?>

<div style="width:110px; float:left;">
<?php echo wp_get_attachment_image( $image->ID, $size="thumbnail", $icon = false, $attr="" ); ?><br>
<?php echo '<input type="checkbox" id="selected" name="image'.$imagenum.'" value="'.$image->ID.'" />Delete Image'; ?>
</div>
<?php endforeach; ?>    
<input type="submit" id="submit" value="click submit" name="submit" />
<input type="hidden" value="" id="ids" />

Below your page, or in footer.php add this:

<script>

jQuery('#submit').click(function() {

jQuery('#ids').val('');
var content = jQuery('body').find('#selected');

jQuery(content).each(function (i) {

    t = jQuery(this).val();

    if (jQuery(this).attr('checked')=='checked') { 
        jQuery('#ids').val(function(i,val){
        return val + t + ',';
        }); 
    };

});

var $ids = jQuery('#ids').val();

jQuery.ajax({
    type        : 'POST',
    url         : '<?php echo admin_url('admin-ajax.php'); ?>',
    data        : { action : 'front_delete', Delete: $ids, postID: <?php echo $post->ID; ?> },
    success     : function(response) {
        if (response="reload") { location.reload(); } else { alert(response); }
        }
    });  
});
</script>

Inside your theme functions.php paste this code:

add_action('wp_ajax_nopriv_front_delete', 'front_delete');
add_action('wp_ajax_front_delete', 'front_delete');

function front_delete() {
    if (!isset($_REQUEST['postID']))
        echo 'Post ID not coming...';

    if (isset($_REQUEST['Delete'])) {

        $sel = explode(',', $_REQUEST['Delete']);
        foreach ($sel as $key) {
            if ($key != '' || $key != '0')
                wp_delete_attachment( $key );
            if (false === wp_delete_attachment( $key ))
                echo 'Image not deleted or error';
        } echo 'reload';
    } else { echo 'No ID coming from your function'; }
die();
}   

If you want to understand it, I can explain … not sure if you want it… 🙂

Leave a Comment