wp_insert_post后无法获取页面模板slug问题排查
WordPress新建页面无法获取自定义模板slug的问题解决
问题描述
我尝试获取新建WordPress页面/文章分配的页面模板slug,已为新建内容分配自定义模板,但创建时error_log输出空字符串;删除文章时反而能获取到已分配的模板slug。
现有代码
function page_template_test($post_id, $post, $update) { $template_slug = get_page_template_slug($post_id); if ($template_slug) { error_log('Template-slug found: ' . $template_slug); } else { error_log('No template-slug not found post ID: ' . $post_id); } } add_action('wp_insert_post', 'page_template_test', 10, 3);
错误日志
AH01071: Got error 'PHP message: No template-slug not found post ID: 6966; PHP message: No template-slug not found post ID: 6967', referer: https://website.org/wp-admin/post-new.php?post_type=page
问题原因
核心问题是wp_insert_post钩子的执行时机过早:
- 新建页面时,WordPress会先创建基础的post记录(此时自定义模板还未写入数据库),
wp_insert_post在这个初始创建阶段就触发,调用get_page_template_slug自然拿不到有效数据。 - 删除文章时,WordPress读取的是已完整保存的post数据(包含之前分配的模板信息),所以此时能获取到slug。
解决方法
方法1:改用save_post钩子并提高优先级
save_post钩子会在post数据完全保存后触发,设置更高优先级(如20)确保模板数据已写入数据库:
function page_template_test($post_id, $post, $update) { // 跳过自动保存和修订版本,避免无效触发 if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) { return; } $template_slug = get_page_template_slug($post_id); if ($template_slug) { error_log('Template-slug found: ' . $template_slug); } else { error_log('No template-slug not found post ID: ' . $post_id); } } add_action('save_post', 'page_template_test', 20, 3);
方法2:直接从$post对象获取模板属性
如果需要更早获取,可以直接读取$post对象的page_template属性,注意排除默认模板情况:
function page_template_test($post_id, $post, $update) { if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) { return; } $template_slug = $post->page_template; if ($template_slug && $template_slug !== 'default') { error_log('Template-slug found: ' . $template_slug); } else { error_log('No template-slug not found post ID: ' . $post_id); } } add_action('save_post', 'page_template_test', 20, 3);
内容的提问来源于stack exchange,提问作者Berry Roelfsema
相关产品推荐
相关产品推荐

