提交表单生成自定义文章后自定义页面模板被删除问题排查求助
问题成因
核心错误是误用了wp_update_post函数创建新文章:
wp_update_post的作用是更新已存在的WordPress文章,当传入的参数数组中没有包含ID字段时,它会默认使用当前全局主查询的文章ID,也就是你承载表单的自定义模板页面的ID,直接把这个页面的文章类型修改为business、状态修改为pending,自然就在页面列表里找不到该模板页,看起来就像被删除了。- 同时你后续添加的自定义字段也都误加到了这个原页面的ID上,没有绑定到新的商家文章上。
修复方法
- 替换创建文章的函数:将
wp_update_post替换为专门用来新增文章的wp_insert_post,该函数会自动生成新的文章ID,不会修改现有内容。 - 新增插入结果判断,避免后续自定义字段操作出错。
- 补充建议:可以添加WordPress nonce字段做表单校验,防止跨站请求伪造攻击。
修改后的核心代码如下:
/* Template Name: Add Business */ global $nameError, $websiteError, $hasError, $emailSent; if(isset($_POST['submitted'])) { // 建议此处先加nonce校验,示例:if ( !isset( $_POST['bus_form_nonce'] ) || !wp_verify_nonce( $_POST['bus_form_nonce'], 'submit_bus_form' ) ) exit; if(trim($_POST['bus_name']) === '') { $nameError = 'Please enter your business name.'; $hasError = true; } else { $bus_name = trim($_POST['bus_name']); } if(trim($_POST['bus_website']) === '') { $websiteError = 'Please enter the website address for your business.'; $hasError = true; } else { $bus_website = trim($_POST['bus_website']); } // 其余字段校验保留 if(!isset($hasError)) { $business_listing = array( 'post_type' => 'business', 'post_author' => 1, 'post_title' => $bus_name, 'post_content' => $bus_desc, 'post_status' => 'pending' ); // 替换为wp_insert_post创建新文章 $post_id = wp_insert_post( $business_listing ); if( !is_wp_error( $post_id ) ) { add_post_meta($post_id, 'bus_website', $bus_website, true); // 其余自定义字段操作保留 $emailSent = true; } else { $hasError = true; } } }
另外你现有HTML代码里的错误提示输出缺少echo,导致错误文本不会显示,需要修改对应位置:
<!-- 原来的写法 --> <span class="error"><?PHP $nameError; ?></span> <!-- 修改为 --> <span class="error"><?php echo $nameError; ?></span>
误删页面恢复方法
如果原来的表单页面已经被修改消失,可以直接操作数据库恢复:
找到你站点的wp_posts表(表前缀根据你实际配置可能不同),筛选post_title为原表单页面标题的条目,将post_type字段值改回page,post_status改回publish,即可在后台页面列表重新看到该页面。
内容的提问来源于stack exchange,提问作者Justin Lucas
相关产品推荐
相关产品推荐

