求问:WordPress编辑文章页面加载前触发的钩子(无需退出)
WordPress编辑文章页预填充字段的可用钩子
有的,你可以用load-post.php和load-post-new.php这两个动作钩子,它们会在编辑已有文章页面和新建文章页面加载前触发,无需退出登录,刚好满足从URL获取值预填充字段的需求。
实现示例代码
下面是一个完整的实现,包含标题、内容和自定义字段的预填充逻辑:
// 针对编辑已有文章和新建文章页面加载时触发 add_action('load-post.php', 'prepopulate_post_fields_from_url'); add_action('load-post-new.php', 'prepopulate_post_fields_from_url'); function prepopulate_post_fields_from_url() { // 检查URL中是否存在需要的参数(示例用custom_title、custom_content、custom_field) if (!isset($_GET['custom_title']) && !isset($_GET['custom_content']) && !isset($_GET['custom_field'])) { return; } global $post; // 可选:跳过已有文章的预填充(如果不需要覆盖已有内容的话) if ($post && $post->ID) { return; } // 预填充文章标题 if (isset($_GET['custom_title'])) { add_filter('default_title', function() { return sanitize_text_field($_GET['custom_title']); }); } // 预填充文章内容 if (isset($_GET['custom_content'])) { add_filter('default_content', function() { return wp_kses_post($_GET['custom_content']); }); } // 预填充自定义字段(示例:假设自定义字段输入框ID为custom_field_input) if (isset($_GET['custom_field'])) { // 用JS填充更可靠,因为新建文章时还没有生成post ID,无法直接写入meta add_action('admin_footer', function() { $field_value = esc_js($_GET['custom_field']); echo "<script> const fieldInput = document.querySelector('#custom_field_input'); if (fieldInput) fieldInput.value = '$field_value'; </script>"; }); } }
关键注意事项
- 安全处理:必须对URL参数做 sanitize/escape 处理,比如用
sanitize_text_field、wp_kses_post、esc_js,避免XSS攻击。 - 页面精准性:
load-post.php和load-post-new.php只会在目标页面触发,比admin_init这类全局后台钩子更高效,无需额外判断页面类型。 - 自定义字段处理:新建文章时还未生成post ID,直接用
update_post_meta会无效,用前端JS填充输入框是更稳妥的方案。
内容的提问来源于stack exchange,提问作者Raul Magdalena Catala
相关产品推荐
相关产品推荐

