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

如何为WordPress特定页面添加Hook 按页面ID限制插件运行范围

实现WordPress插件仅指定页面ID生效的操作方法

核心逻辑是在插件功能代码外层套WordPress原生的页面判断条件,且确保判断逻辑在WordPress全局数据初始化完成后执行。

步骤1:获取目标页面的ID

进入WordPress后台「页面」-「所有页面」,将鼠标悬停在你指定的目标页面的「编辑」按钮上,浏览器底部显示的链接中post=后面的数字就是该页面的ID,比如链接为wp-admin/post.php?post=12&action=edit,则页面ID为12。

步骤2:在插件代码中加入页面判断逻辑

所有需要仅在目标页面执行的功能代码,都要绑定到WordPress的template_redirect钩子(前端页面加载阶段触发)中,配合is_page(页面ID)判断执行。

代码示例

// 将以下代码写入你的插件主PHP文件中
add_action('template_redirect', 'my_plugin_run_on_specified_page');
function my_plugin_run_on_specified_page() {
    // 替换括号内的数字为你自己的目标页面ID
    if ( is_page( 12 ) ) {
        // 此处放置你插件的所有功能代码
        // 示例:加载插件的自定义样式、脚本
        wp_enqueue_style('my-plugin-custom-css', plugins_url('assets/css/style.css', __FILE__));
        wp_enqueue_script('my-plugin-custom-js', plugins_url('assets/js/main.js', __FILE__), array('jquery'), '1.0', true);
        // 示例:修改页面内容输出
        add_filter('the_content', 'my_plugin_append_custom_content');
    }
}

// 自定义功能回调示例
function my_plugin_append_custom_content($origin_content) {
    $custom_block = '<div class="plugin-custom-block">插件生成的专属内容</div>';
    return $origin_content . $custom_block;
}

常见适配场景说明

  • 要同时适配多个指定页面时,可给is_page()传入ID数组,写法为is_page( array(12, 18, 35) ),即可在ID为12、18、35的三个页面均触发插件逻辑
  • 若需要在后台编辑该目标页面时也触发插件逻辑,使用以下判断条件即可:
    add_action('current_screen', 'my_plugin_run_on_page_edit_screen');
    function my_plugin_run_on_page_edit_screen() {
        $current_screen = get_current_screen();
        if ( $current_screen->id === 'page' && isset($_GET['post']) && intval($_GET['post']) === 12 ) {
            // 此处放置后台编辑页面时要执行的代码
        }
    }
    
  • 不要直接在插件主文件的根层级(钩子外)写功能执行代码,此时WordPress的页面数据还未初始化,is_page()判断会失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:24:04