如何在主题目录的自定义PHP文件中引入WordPress页眉与页脚?
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:
1. Use it as a WordPress Page Template (Recommended for public-facing pages)
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, likepage-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 namedcustom-widget.php, you’d write:
(No need to add the<?php get_template_part('custom-widget'); ?>.phpsuffix 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'; ?>
3. Manually Load WordPress Core (Not Recommended)
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

