如何检测WordPress FSE页面所用模板?求替代get_page_template_slug()的PHP函数
在WordPress全站点编辑器(FSE)中检测页面模板的方法
在FSE环境下,传统的get_page_template_slug()函数不再生效——因为FSE使用的是块主题模板体系,而非旧版的PHP页面模板文件,该函数仅针对后者设计。以下是替代方案:
核心替代方法
1. 获取单个页面的模板标识
要获取指定页面使用的FSE模板slug,直接读取页面的元数据即可:
$template_slug = get_post_meta( get_the_ID(), '_wp_template', true );
返回值类似page-about或custom/my-custom-template,对应块主题中定义的模板标识。
2. 获取模板的详细信息
如果需要模板的标题、描述等完整信息,可结合get_block_template()函数:
$template_slug = get_post_meta( get_the_ID(), '_wp_template', true ); if ( $template_slug ) { $block_template = get_block_template( $template_slug, 'wp_template' ); // 输出模板名称 echo $block_template->title; // 输出模板描述 echo $block_template->description; }
3. 全局上下文检测当前模板
如果在主题全局文件(如functions.php、header.php)中需要获取当前加载的FSE模板,可使用查询变量:
$current_template_slug = get_query_var( 'wp_template' );
注意事项
- 仅当站点使用块主题且开启FSE时,上述方法才有效;若仍使用传统PHP主题,
get_page_template_slug()依然可用。 get_block_template()函数需要WordPress 5.9及以上版本支持。
内容的提问来源于stack exchange,提问作者user2888697
相关产品推荐
相关产品推荐

