WordPress - Как предотвратить повторную отправку формы?
Как я могу предотвратить повторную отправку формы в WordPress?
У меня есть пользовательская страница с формой:
<?php
/*
Template Name: Submission
*/
get_header(); ?>
<!-- page article -->
<?php
// Include the page nav.
get_template_part( 'nav-page', 'nav' );
?>
<!-- container -->
<div class="container">
<!-- item -->
<div class="col-md-4">
<!-- content -->
<div class="multimedia-submission-text-block">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'content-page-article-submission', 'page psubmission' );
// End the loop.
endwhile;
?>
</div>
<!-- content -->
</div>
<!-- item -->
<!-- form -->
<div class="col-md-8">
<?php
// Set default variables.
$anon_submission_name = '';
$anon_submission_email = '';
$anon_submission_biography = '';
$success = false;
$error = false;
if (
isset($_POST['anon_submission_form_create_post_submitted'])
&& wp_verify_nonce($_POST['anon_submission_form_create_post_submitted'],'anon_submission_form_create_post')
) {
$anon_submission_name = trim($_POST['anon_submission_name']);
$anon_submission_email = trim($_POST['anon_submission_email']);
$anon_submission_biography = trim($_POST['anon_submission_biography']);
if ($anon_submission_title != ''
&& $anon_submission_name != ''
&& $anon_submission_email != ''
&& $anon_submission_biography != ''
) {
// post_author Take (int) The ID of the user who added the post. Default is the current user ID
$post_data = array(
'post_title' => $anon_submission_title,
// 'post_content' => $anon_submission_description,
'post_status' => 'pending',
'post_author' => 1, // admin user id
'post_type' => 'post'
);
// Insert the post and get its id.
$post_id = wp_insert_post($post_data);
if($post_id){
// Save other info in meta.
update_post_meta($post_id,'anon_submission_meta_name', $anon_submission_name);
update_post_meta($post_id,'anon_submission_meta_email', $anon_submission_email);
update_post_meta($post_id,'anon_submission_meta_biography', $anon_submission_biography);
$success = true;
echo '<p class="alert alert-success"><span class="close" data-dismiss="alert">×</span> Work submitted and awaiting moderation. Thank you for your submission.</p>';
}
} else { // author or text field is empty
$error = true;
echo '<p class="alert alert-danger"><span class="close" data-dismiss="alert">×</span> Work NOT submitted! Please correct the error(s) below.</p>';
}
}
?>
<form class="form-submission" method="post" action="<?php echo $current_url . '?' . mt_rand(1, 1000); ?>">
<?php wp_nonce_field('anon_submission_form_create_post', 'anon_submission_form_create_post_submitted'); ?>
<div class="row">
<!-- item -->
<div class="col-md-6">
<div class="form-group<?php if ($error && empty($anon_submission_name)): ?> has-error<?php endif; ?>">
<label for="inputName">Name (required)</label>
<input type="text" class="form-control" id="input-name" placeholder="Name" name="anon_submission_name" value="<?php if ($error) echo $anon_submission_name; ?>">
</div>
<div class="form-group<?php if ($error && empty($anon_submission_email)): ?> has-error<?php endif; ?>">
<label for="inputEmail">Email Address (required)</label>
<input type="email" class="form-control" id="input-email" placeholder="Email" name="anon_submission_email" value="<?php if ($error) echo $anon_submission_email; ?>">
</div>
<div class="form-group<?php if ($error && empty($anon_submission_biography)): ?> has-error<?php endif; ?>">
<label for="inputMessage">Biography (required)</label>
<textarea class="form-control" rows="6" placeholder="Biography" name="anon_submission_biography"><?php if ($error) echo $anon_submission_biography; ?></textarea>
</div>
</div>
<!-- item -->
</div>
<button type="submit" class="btn btn-default no-gradient">Submit</button>
</form>
</div>
<!-- form -->
</div>
<!-- container -->
<?php get_footer(); ?>
Вы всегда получаете всплывающее окно "Подтверждение повторной отправки формы", когда нажимаете кнопку обновления, указали ли вы информацию для всех обязательных полей или нет.
Есть идеи?
РЕДАКТИРОВАТЬ:
Перенаправление:
...
} else { // author or text field is empty
wp_redirect( home_url() );
}
ошибка:
Предупреждение: невозможно изменить информацию заголовка - заголовки уже отправлены (вывод начался с /var/www/project-path/wp-includes/embed.php:363) в /var/www/project-path/wp-includes/pluggable. PHP на линии 1167
2 ответа
Не записывайте свои действия в файл шаблона. Напишите свои действия в functions.php темы
add_action('init','your_function_name');
function your_function_name(){
if($_POST['your_var']){
//...... do what ever
// then if neeeded do wp_redirect
}
}
Надеюсь, что это решит вашу проблему.
Быстрое решение:
Я положил код обработки:
<?php
// Set default variables.
$anon_submission_name = '';
$anon_submission_email = '';
$anon_submission_biography = '';
$success = false;
$error = false;
....
До:
<?php
/*
Template Name: Submission
*/
get_header(); ?>
А затем перенаправить после проверки и отправки формы:
// Redirect to prevent form resubmission.
wp_redirect(get_permalink($post->ID) . '?success=true');