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 } ?>
You can do it via ajax, first, let’s change your current function to this:
Below your page, or in footer.php add this:
Inside your theme functions.php paste this code:
If you want to understand it, I can explain … not sure if you want it… 🙂
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’