Hi I have a form that adds attachments to a post, however when the form posts it obviously doesn’t show the post with the new attachment echoing “your file has been uploaded”. When the user refreshes the page (to try and show their new attachment) the form posts again!

Is it possible to either (1) stop the form posting again on refresh, (2) automatically refresh the page to display the post with its new attachment?? (2 is way better)

<?php $post_id = $post->ID;
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$id = media_handle_upload('async-upload', $post_id); //post id of Client Files page
unset($_FILES);
if ( is_wp_error($id) ) {
    $errors['upload_error'] = $id;
    $id = false;
}

if ($errors) {
    echo "<p>There was an error uploading your file.</p>";
} else {
    echo "<p>Your file has been uploaded.</p>";
}
}

?>
<form id="file-form" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST">

<p id="async-upload-wrap"><label for="async-upload">upload</label>
<input type="file" id="async-upload" name="async-upload"> <input type="submit" value="Upload" name="html-upload"></p>

<p><input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" /></p>

<p><input type="submit" value="Save all changes" name="save" style="display: none;"></p>
</form>

Thanks! 🙂

9 s
9

Instead of …

} else {
    echo "<p>Your file has been uploaded.</p>";
}

… redirect to another address on success:

} else {

    $new_url = add_query_arg( 'success', 1, get_permalink() );
    wp_redirect( $new_url, 303 );
    exit;
}

Status code 303 triggers a GET request:

This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

In your form handler check first if $_GET['success'] is set and its value is 1, then print a success message. The visitor can reload this page again and again – and nothing will be sent.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *