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

如何为WordPress单个插件生成的页面单独添加.php后缀

解决方案

你可以通过组合使用WordPress重写规则、永久链接过滤钩子实现单个页面自定义.php后缀,不会影响其他页面的链接结构,具体实现步骤如下:

步骤1:添加自定义重写规则

将以下代码添加到你当前主题的functions.php文件,或者你的自定义插件的代码文件中:

// 添加单个页面的.php重写规则
function custom_single_page_php_rewrite_rule() {
    // 替换成你目标页面的slug,示例为myfile
    $target_slug = 'myfile';
    add_rewrite_rule(
        '^' . $target_slug . '\.php$',
        'index.php?pagename=' . $target_slug,
        'top'
    );
}
add_action('init', 'custom_single_page_php_rewrite_rule');

// 允许WordPress识别.php后缀的查询
function custom_allow_php_suffix_in_query($vars) {
    if (isset($_SERVER['REQUEST_URI']) && preg_match('/\/myfile\.php$/', $_SERVER['REQUEST_URI'])) {
        $vars['pagename'] = 'myfile';
    }
    return $vars;
}
add_filter('request', 'custom_allow_php_suffix_in_query');

步骤2:过滤目标页面的永久链接输出

添加以下代码,让WordPress生成该页面的链接时自动带上.php后缀,不需要手动修改页面固定链接,也不会出现点号被转成-php的问题:

function custom_append_php_to_single_page_link($permalink, $post) {
    // 替换成你目标页面的slug,也可以用$post->ID == 你的页面ID来判断
    if ($post->post_type == 'page' && $post->post_name == 'myfile') {
        $permalink = rtrim($permalink, '/') . '.php';
    }
    return $permalink;
}
add_filter('post_type_link', 'custom_append_php_to_single_page_link', 10, 2);
add_filter('page_link', 'custom_append_php_to_single_page_link', 10, 2);

步骤3:刷新重写规则

代码添加完成后,进入WordPress后台 设置 -> 固定链接,直接点击「保存更改」,不需要修改任何配置,即可刷新重写规则让配置生效。

提示:如果你后续修改了目标页面的slug,需要同步修改代码里的目标slug值,再刷新一次重写规则即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:36:01