WordPress插件开发:表单提交后重定向至新创建文章的问题及解决方案
Hey Colin, let's tackle those two issues with your WordPress post-creation plugin. I'll break down straightforward solutions for both the permalink passing problem and the blank page issue when using exit() after redirects.
Problem 1: Getting the New Post's Permalink & Passing It to Your Init Function
Right now, your create_post() and myInit() functions are operating independently, which is why you can't access the new post ID in myInit(). The cleanest fix isn't using sessions—it's restructuring your code to run create_post() directly inside myInit() once validation passes, so you can grab the post ID immediately.
Here's the core idea:
- Modify
create_post()to return the new post ID ($pid) once the post is successfully created. - In
myInit(), after validation clears, callcreate_post()and store the returned ID. Then use that ID to generate the permalink for the redirect.
Problem 2: Blank Page When Using exit() After Redirect
Using PHP's native header() function can cause issues in WordPress because hidden output (like whitespace from theme/plugin files) might be sent before your redirect runs. WordPress has a built-in wp_redirect() function that handles output buffering properly, which avoids this blank page problem. Always pair wp_redirect() with exit; to stop further code execution—this is safe and recommended when using WordPress's redirect tool.
Modified Code Example
I've updated your code with these fixes, plus some additional bug fixes (like the missing $post_type definition):
// Modified create_post() to return the new post ID function create_post(){ if(!is_user_logged_in()) { echo "<h2 style='text-align:center;'>User must be login for add post!</h2>"; return false; // Return false if user isn't logged in } if(isset($_POST['ispost'])) { global $current_user; get_currentuserinfo(); $user_id = $current_user->ID; $post_title = $_POST['title']; $post_content = $_POST['sample_content']; $category = $_POST['category']; // Fixed: Define your post type (adjust to your custom type if needed) $post_type = 'post'; $new_post = array( 'post_title' => $post_title, 'post_content' => $post_content, 'post_status' => 'publish', 'post_type' => $post_type, 'post_category' => $category ); $pid = wp_insert_post($new_post); if(!$pid) return false; // Return false if post creation fails add_post_meta($pid, 'meta_key', true); // Handle file uploads if (!function_exists('wp_generate_attachment_metadata')) { require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); } $attach_id = 0; if ($_FILES) { foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) { // Optional: Add error handling here continue; } $attach_id = media_handle_upload( $file, $pid ); } } if ($attach_id > 0) { update_post_meta($pid, '_thumbnail_id', $attach_id); } return $pid; // Return the new post ID to the caller } return false; } add_action('init', 'myInit'); function myInit() { if (isset($_POST['ispost'])) { $errors = myFormValidation(); if (empty($errors)) { // Call create_post() and get the new post ID $new_post_id = create_post(); if($new_post_id) { // Use WordPress's wp_redirect instead of raw header() wp_redirect(get_permalink($new_post_id)); exit; // This is safe now with wp_redirect() } else { // Handle post creation failure echo "<h2 style='text-align:center;'>Failed to create post!</h2>"; } } else { // Display validation errors foreach($errors as $error) { echo "<p style='color:red;'>$error</p>"; } } } }
Key Fixes Explained:
- Permalink Passing: By calling
create_post()directly inmyInit(), we get the$new_post_idimmediately—no sessions needed. This is the most efficient and WordPress-standard approach. - Redirect & Exit Issue: Switched from
header()towp_redirect(), which manages output buffering to prevent accidental early output that causes blank pages. Addingexit;afterwp_redirect()is correct here—it stops any further code from running, which is necessary for a clean redirect. - Other Improvements: Added a definition for
$post_type(it was missing in your original code), added error checks for post creation failure, and cleaned up file upload handling.
Quick Security Note:
Make sure your myFormValidation() function properly sanitizes and validates all user input (like $_POST['title'] and file uploads) to avoid security risks like SQL injection or malicious file uploads.
内容的提问来源于stack exchange,提问作者Colin

