WordPress使用session跳转时重定向到旧文章而非新创建文章如何解决?
问题修复方案
核心问题定位
- 钩子执行顺序错误:绑定在
init上的跳转函数myInit执行时机早于create_post函数,跳转时读取的是上一次请求存储的旧$_SESSION['pid']值 - 代码语法错误:设置文章缩略图后的session赋值逻辑中,
$pid是wp_insert_post返回的整数类型文章ID,并非WP_Post对象,$pid->post_name属于无效调用,会导致赋值失败 - WordPress默认未开启session支持,未主动开启的情况下session变量无法正常存储
- 硬编码拼接文章URL的方式兼容性差,易因固定链接规则变动出现跳转错误
修复步骤
1. 提前开启WordPress Session支持
在插件代码最前端添加session初始化逻辑,优先级设为最高:
add_action('init', 'custom_plugin_session_start', 1); function custom_plugin_session_start() { if (!session_id()) { session_start(); } }
2. 调整钩子执行顺序,修复create_post代码错误
将create_post也绑定到init钩子,优先级高于跳转函数,确保先创建文章存储session再执行跳转,同时修复原有代码中的语法错误、未定义变量问题:
add_action('init', 'create_post', 5); // 优先级5,早于跳转函数 function create_post(){ global $current_user; $post_type = 'post'; // 按需修改为你的自定义文章类型别名 $attach_id = 0; // 初始化附件ID,避免无图上传时报错 if(is_user_logged_in()) { if(isset($_POST['ispost'])) { get_currentuserinfo(); $user_login = $current_user->user_login; $user_email = $current_user->user_email; $user_firstname = $current_user->user_firstname; $user_lastname = $current_user->user_lastname; $user_id = $current_user->ID; $post_title = sanitize_text_field($_POST['title']); // 补充表单字段过滤,提高安全性 $sample_image = $_FILES['sample_image']['name']; $post_content = wp_kses_post($_POST['sample_content']); $category = array_map('intval', $_POST['category']); $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 (is_wp_error($pid)) return; // 文章创建失败直接返回 add_post_meta($pid, 'meta_key', true); $_SESSION['new_post_id'] = $pid; // 直接存储文章ID,后续用原生函数获取链接更稳妥 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'); } if ($_FILES) { foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) { return "upload error : " . $_FILES[$file]['error']; } $attach_id = media_handle_upload( $file, $pid ); } } if ($attach_id > 0) { update_post_meta($pid, '_thumbnail_id', $attach_id); } } } else { echo "<h2 style='text-align:center;'>User must be login for add post!</h2>"; } }
3. 调整跳转函数逻辑,修复跳转问题
降低跳转函数的优先级,确保在文章创建完成后执行,跳转后销毁session变量避免重复跳转:
add_action('init', 'myInit', 20); // 优先级20,晚于文章创建函数 function myInit() { if (isset($_POST['ispost'])) { $errors = myFormValidation(); if (empty($errors) && isset($_SESSION['new_post_id'])) { $url = get_permalink($_SESSION['new_post_id']); // 用WordPress原生函数生成链接,兼容所有固定链接规则 unset($_SESSION['new_post_id']); // 用完即删,避免后续请求误跳转 wp_redirect($url); exit; // wp_redirect后必须加exit终止后续代码执行 } } }
额外优化建议
- 所有表单提交的字段都要做 sanitize 过滤,避免SQL注入、XSS攻击
- 可以不用session实现,同一个init请求中创建文章得到的$pid可以直接在跳转逻辑中共享,减少session依赖
- 新增文章创建失败的错误提示,提高用户体验
内容的提问来源于stack exchange,提问作者Colin Guild
相关产品推荐
相关产品推荐

