WordPress区块主题中如何为特定区块模板入队加载CSS文件?
问题场景
使用WordPress区块主题(Block Theme)范式开发主题时,需要为所有调用templates/foo.html模板的页面加载foo.css文件。
传统主题开发中用于判断页面模板的get_page_template_slug()函数仅支持PHP格式的传统页面模板,在区块主题场景下无返回值,无法实现CSS的条件入队。
已尝试的调试代码如下:
function foo_enqueue() { echo '<pre>'; print_r( get_page_template_slug(get_the_ID()) ); echo '</pre>'; } add_action( 'wp_enqueue_scripts', 'foo_enqueue' );
失效原因
get_page_template_slug()的核心逻辑是读取文章元数据中存储的_wp_page_template字段值,这个字段仅在用户手动选择传统PHP页面模板时才会被赋值。区块主题下自动匹配、或者用户选择的HTML格式区块模板不会写入该字段,因此函数返回空值,无法作为判断依据。
可行解决方案
区块主题下可以通过全局变量$_wp_current_template_id获取当前页面加载的区块模板标识,在wp_enqueue_scripts钩子中做判断即可实现条件入队,代码示例如下:
function foo_template_enqueue_styles() { // 非区块主题直接终止逻辑 if ( ! wp_is_block_theme() ) { return; } global $_wp_current_template_id; // 匹配templates/foo.html模板,模板ID格式为「主题slug//模板文件名」 if ( strpos( $_wp_current_template_id, '//foo' ) !== false ) { wp_enqueue_style( 'foo-style', // 替换为你主题内foo.css的实际存放路径 get_template_directory_uri() . '/foo.css', [], wp_get_theme()->get('Version') ); } } add_action( 'wp_enqueue_scripts', 'foo_template_enqueue_styles' );
注意事项
- 上述判断逻辑用
strpos做匹配,兼容PHP7.0及以上版本,无需担心低版本环境报错 - 如果你的
foo.html是带Template Name头部标注的自定义页面模板,这个判断逻辑同样生效 - 如果是子主题场景,把代码中的
get_template_directory_uri()替换为get_stylesheet_directory_uri()即可正常加载子主题内的CSS文件
内容的提问来源于stack exchange,提问作者Doug Beney
相关产品推荐
相关产品推荐

