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

如何在主题目录的自定义PHP文件中引入WordPress页眉与页脚?

解决WordPress主题自定义PHP文件调用get_header()报错的问题

Hey there, let's figure out why you're hitting that "Undefined function get_header()" error and get it fixed the right way.

First, the root cause: get_header() is a WordPress core template function, but it only works after WordPress has fully loaded all its core files. If you're running your custom PHP file directly (like typing its URL into the browser), WordPress hasn't been initialized at all—so those built-in template functions don't exist yet.

Here are the proper ways to handle this, depending on what you need the file to do:

If you want this file to be accessible as a page on your site (e.g., yourdomain.com/my-custom-page/):

  • Rename your custom file to follow WordPress's page template naming convention: page-{slug}.php (replace {slug} with something unique, like page-custom-content.php).
  • Go to your WordPress admin, create a new page. In the Page Attributes panel, you'll see a Template dropdown—select the template you just created (it’ll show up with a human-readable name based on your filename).
  • Now when you visit that page's URL, WordPress will automatically load its core system before running your file, so get_header(), get_footer(), and other template functions will work perfectly.

2. Include it as a Theme Partial File

If your custom file is just a snippet of code you want to reuse in other theme templates (like in header.php or a post template):

  • Use WordPress's built-in get_template_part() function to pull it in. For example, if your file is named custom-widget.php, you’d write:
    <?php get_template_part('custom-widget'); ?>
    
    (No need to add the .php suffix here—WordPress handles that automatically.)
  • If you prefer using include/require, always use WordPress's path constants to avoid broken paths if your theme directory changes:
    <?php require get_template_directory() . '/custom-widget.php'; ?>
    

If you absolutely need to run the file directly (browsing to its URL directly), you can manually load WordPress's core at the top of your file:

<?php
// Adjust the path to wp-load.php if your WordPress is installed in a subdirectory
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');

// Now you can use get_header()
get_header();

// Your custom code here

get_footer();
?>

Note: This approach is not ideal—it bypasses WordPress's normal template flow and can introduce security risks. Stick to the first two methods whenever possible.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:05:30