WordPress插件中表单提交后重定向至当前页面的实现
Hey there! Let's get that page refresh working for your WordPress form. The issue right now is that when you submit the form, it sends data to admin-post.php which processes it, but doesn't redirect you back to the original page. Here are two reliable solutions to fix this:
Solution 1: Server-Side Redirect (Simplest Approach)
This method uses WordPress built-in functions to redirect the user back to the page where they submitted the form right after processing the data.
Step 1: Update Your Form Processing Function
In your plugin code where you handle the send_nl action, add a redirect using wp_redirect() and wp_get_referer():
// Hook into admin_post for logged-in and non-logged-in users add_action('admin_post_send_nl', 'handle_send_nl_submission'); add_action('admin_post_nopriv_send_nl', 'handle_send_nl_submission'); function handle_send_nl_submission() { // 👉 Insert your existing form processing logic here (validation, saving data, etc.) // Redirect back to the original page where the form was submitted $original_page = wp_get_referer(); if ($original_page) { // Optional: Add a success parameter to show a confirmation message later $redirect_url = add_query_arg('nl_submitted', 'success', $original_page); wp_redirect($redirect_url); } else { // Fallback: Redirect to homepage if no referrer is found wp_redirect(home_url()); } exit; // Always exit after wp_redirect to stop further execution }
Step 2: (Optional) Show a Success Message
If you added the nl_submitted=success parameter, you can display a confirmation message on your form page:
// Add this where you want the message to appear (above the form, for example) if (isset($_GET['nl_submitted']) && $_GET['nl_submitted'] === 'success') { echo '<div class="success-message">Form submitted successfully!</div>'; }
Solution 2: AJAX Submission (No Full Page Refresh)
If you prefer a smoother user experience without reloading the entire page, use AJAX to submit the form. You can optionally trigger a refresh after success if needed.
Step 1: Modify the Form
Update your form to include a unique ID and a security nonce (critical for WordPress security):
<form id="nl-submit-form" method="post"> <input type="hidden" name="action" value="send_nl"> <input type="hidden" name="_ajax_nonce" value="<?php echo wp_create_nonce('send_nl_secure'); ?>"> <input type="text" name="nl_title" placeholder="Title"> <textarea name="nl_text" placeholder="Message"></textarea> <input type="submit" name="submit_nl" value="Submit"> </form>
Step 2: Add AJAX Processing PHP
Add this to your plugin code to handle the AJAX request:
// Hook into wp_ajax for logged-in and non-logged-in users add_action('wp_ajax_send_nl', 'handle_ajax_nl_submission'); add_action('wp_ajax_nopriv_send_nl', 'handle_ajax_nl_submission'); function handle_ajax_nl_submission() { // Validate the security nonce first if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce($_POST['_ajax_nonce'], 'send_nl_secure')) { wp_send_json_error('Invalid request.'); exit; } // Sanitize and process form data $title = sanitize_text_field($_POST['nl_title']); $text = sanitize_textarea_field($_POST['nl_text']); // 👉 Insert your form processing logic here (save data, send email, etc.) // Return success response wp_send_json_success('Form submitted successfully!'); }
Step 3: Add AJAX JavaScript
Add this script to your plugin (enqueue it properly or place it in your theme's functions.php with wp_enqueue_script()):
jQuery(document).ready(function($) { $('#nl-submit-form').on('submit', function(e) { e.preventDefault(); // Stop the default form submission const formData = $(this).serialize(); $.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'POST', data: formData, success: function(response) { // Show success message and reset form alert(response.data); $('#nl-submit-form')[0].reset(); // Optional: Uncomment below to refresh the page after success // location.reload(); }, error: function(response) { alert('Oops! ' + response.responseJSON.data); } }); }); });
Both solutions will resolve your page refresh issue—pick the one that fits your user experience needs best!
内容的提问来源于stack exchange,提问作者Ali Elkhaiat

