WordPress餐厅自定义文章类型元数据保存失败:save钩子未触发
自定义文章类型(Restaurant)元数据无法保存的问题修复
你的代码存在三个关键问题,导致save_restaurant_meta_box函数未正常执行或提前返回:
1. 元数据框未输出Nonce验证字段
save_restaurant_meta_box函数开头会检查restaurant_meta_box_nonce,但你的display_restaurant_meta_box函数里没有输出这个nonce字段,导致验证失败直接return。
修复:在display_restaurant_meta_box函数开头添加nonce输出:
function display_restaurant_meta_box( $post ) { if (defined('WP_DEBUG') && constant('WP_DEBUG')) echo "Inside " . __FUNCTION__ . "<br>"; // 添加nonce验证字段 wp_nonce_field( 'restaurant_meta_box', 'restaurant_meta_box_nonce' ); // 原有字段代码... }
2. 权限检查逻辑错误
你的自定义文章类型ht_restaurant的capability_type设为page,但保存时的权限检查判断的是$_POST['post_type'] == 'page',而实际$_POST['post_type']是ht_restaurant,导致权限验证不通过返回。
修复:修改save_restaurant_meta_box里的权限检查部分:
// 检查用户权限 if ( 'ht_restaurant' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) return $post_id; } elseif ( ! current_user_can( 'edit_post', $post_id ) ) { return $post_id; }
3. register_meta的Object Type参数错误
register_meta的第一个参数应该是对象类型(如post、user),而不是自定义文章类型的slug。你传入ht_restaurant是错误的,应该改为post。
修复:修改register_restaurant_custom_fields函数:
register_meta( 'post', // 改为post 'restaurant_address', array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', // 建议添加 sanitize 回调 'auth_callback' => function() { return current_user_can('edit_posts'); } // 建议添加权限验证回调 ) ); register_meta( 'post', // 改为post 'restaurant_phone', array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'auth_callback' => function() { return current_user_can('edit_posts'); } ) );
额外优化建议
- 移除
save_restaurant_meta_box里的echo语句,因为保存动作是后台执行的,echo会干扰页面跳转,建议用error_log代替调试输出:error_log("Saved restaurant_address: " . $_POST['restaurant_address']); save_post钩子的参数设置:你的函数只接受$post_id,所以add_action不需要传第4个参数2,保持默认即可:add_action("save_post", 'save_restaurant_meta_box');
内容的提问来源于stack exchange,提问作者Mehdi Haghgoo
相关产品推荐
相关产品推荐

