At the top of the page I get a url:
$posturl = $_GET['posturl'];
Works, I got the URl.
The I have a series of checkboxes to delete attachments within a form post:
<form action="" method="post">
<?php
$attachments = get_posts(array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' =>'any',
'post_parent' => $_GET['post_id']
));
if ($attachments) {
foreach ( $attachments as $attachment ) {
$myNewImg = wp_get_attachment_url( $attachment->ID );
$pathtofile = $myNewImg;
$info = pathinfo($pathtofile);
if ( ($info["extension"] == "jpg") || ($info["extension"] == "png") || ($info["extension"] == "JPG") || ($info["extension"] == "jpeg") || ($info["extension"] == "gif") ) { ?>
<img src="<?php echo $myNewImg; ?>" class="bnr_img img-fluid mx-auto d-block" alt="">
<input type="checkbox" class="img_delete" name="img_delete[]" value="<?php echo $attachment->ID; ?>">
<?php } else { ?>
<video src="<?php echo $myNewImg; ?>" controls></video>
<input type="checkbox" class="img_delete" name="img_delete[]" value="<?php echo $attachment->ID; ?>">
<?php }
}
}
?>
<input class="btn btn-dark" type="submit" name="delete_media" value="Delete media">
</form>
All works fine, I get the media attachments and a checkbox next to it:
I now want to delete media files checked, so they’re an array (img_delete[]) so I do:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['delete_media'])) {
foreach($_POST['img_delete'] as $value) {
wp_delete_attachment( $value, true);
}
header('Location: '.$posturl);
}
}
?>
It’s ok but:
- page doesn’t refresh
- page stays there but it only shows one item (even tho 2 have been deleted)
- if i refresh the page, then I see both have been deleted
So basically I’m trying to redirect the page so that user sees the live page without media attachments.
3
Answers
you can use simple javascript for this like below –
Whenever you want to redirect using a
header()
in PHP, you should alwaysexit()
afterwards as explained here.Also, make sure you are redirecting before any output is being sent. Otherwise you will end up with
headers already sent
warnings and the redirect will not work.Also, for this, you should be using wp_safe_redirect() or wp_redirect() for this: