3

I am trying to make a simple media manager on the front end of my posts, as my site will have many authors. I want to give them the ability to delete any picture attachments that they have uploaded to their posts ( without having access to the media manager, because I want this to be mobile compatible).

From my research online I came up with the following code which doesn't work. It displays the thumbnail along with the check box asking for the image to be deleted, but when I press submit, the page reloads and no change is seen ( the attachment has not been deleted).

Can you guys help me to get this to work please?

 <?php
$user_id = get_current_user_id();
if ( $user_id == $EM_Event->event_owner ){
?> 
<?php
if (isset($_POST['submit'])) {
      $i = 1;
   while ($i < 13) {                
    if (isset($_POST['deleteimage'.$i])) {
        $value = $_POST['deleteimage'.$i];
        if ($value !== '') {
            wp_delete_attachment($value);
        }                       
    }               
$i++;
}
}

$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, 'thumbnail'); ?><br>
                <?php echo $image->ID; ?>
                <?php echo '<input type="checkbox" name="deleteimage'.$imagenum. '"        value="'.$image->ID.'" />Delete Image'; ?>
            </div>
       <?php endforeach; ?>
        <form><input type="submit" value="click submit" name="submit" />    </form>
  <?php } ?>
3

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... :)

  • I forgot, you can delete $imagenum vars from this code, also from input name – Santoro May 2 '13 at 15:34
  • Thanks man, it worked. I'll need to study your code a bit further so I can fully understand it. Thanks anyways. – Adzay May 2 '13 at 19:17
  • Hi I found an issue. If the page is refreshed the image is uploaded again. I have to go to another page to prevent that from happening again – Adzay May 2 '13 at 19:37
  • It can't happen, maybe you have another function that is firing when the page is loaded that is uploading your image again – Santoro May 2 '13 at 23:04
  • Hi, Sorry to bother you again. I just realized a bug. Your answer gives me all the attached images in one 'row' (or one after the other). I just realized now that only the first image in that row can be deleted. This means that If i select the check box for the second or last image, it will not delete. I will have to delete the first image in order to delete the second image. – Adzay May 23 '13 at 14:36
0

Each ID has to be unique, so the checkbox for your image is only applying the ID to the first image instead of all of them. To make this code work you just need to change the selected ID to a selected class - this will mean that the code is used for all items not just one.

In the code change remove id="selected" and replace with class="selected"

In the script where it has the find command, remove '#selected' and replace with '.selected'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.