You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取当前页面加载的Gutenberg区块模板内容并检测短代码

高效获取当前页面Gutenberg模板ID并检测短代码

一、快速获取当前模板ID

无需复杂逻辑,直接利用WordPress加载区块模板时生成的全局变量:

// 检查是否处于区块模板页面
if ( isset( $GLOBALS['block_template'] ) && $GLOBALS['block_template'] instanceof WP_Block_Template ) {
    $current_template_id = $GLOBALS['block_template']->id;
}

如果需要在钩子中获取,可通过template_include拦截:

add_filter( 'template_include', function( $template_path ) {
    global $block_template;
    if ( $block_template instanceof WP_Block_Template ) {
        $current_template_id = $block_template->id;
        // 在这里处理模板ID相关逻辑
    }
    return $template_path;
} );

二、获取模板内容并检测短代码

拿到ID后,用get_block_template()获取完整模板内容,再用内置函数检测短代码:

// 优先获取全局变量中的模板对象
$template = $GLOBALS['block_template'] ?? null;

if ( $template instanceof WP_Block_Template && ! empty( $template->content ) ) {
    // 检测目标短代码,替换成你的短代码标签
    if ( has_shortcode( $template->content, 'your-target-shortcode' ) ) {
        // 短代码存在时的逻辑
        // 比如:do_action('shortcode_found_in_template');
    }
}

// 若全局变量未生效,可通过ID二次获取(确保兼容性)
if ( empty( $template ) && isset( $current_template_id ) ) {
    $template = get_block_template( $current_template_id );
    if ( $template && has_shortcode( $template->content, 'your-target-shortcode' ) ) {
        // 执行对应逻辑
    }
}

关键优势

  • 无需遍历所有wp_template记录,仅针对当前页面使用的模板操作,效率和读取$post_content一致
  • 利用WordPress内置函数has_shortcode(),比自定义正则更可靠,能兼容短代码的各种写法(带参数、嵌套等)
  • 全局变量$block_template是WordPress官方在加载区块模板时自动赋值的,稳定性有保障

内容的提问来源于stack exchange,提问作者DFakdkmnadDlakdkd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 21:05:05