如何在自定义PHP文件中调用WordPress主题的页眉和页脚?
get_header() Undefined Error in WordPress Custom PHP Files Hey there! That error pops up because your custom PHP file isn't hooked into WordPress's core environment—so it doesn't recognize built-in template functions like get_header(). Let's break down the solutions based on what you're trying to build:
1. Quick Fix: Manually Load WordPress Core
If your custom file lives directly in your theme folder (e.g., wp-content/themes/your-theme/my-custom-file.php), add this code at the very top of the file to load WordPress's core files:
<?php // Load WordPress core (adjust the path if your WP is in a subdirectory) require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php'); // Now you can use get_header() and other WP functions normally get_header(); // Your custom content goes here echo '<div class="custom-page-content"><h1>My Custom Page</h1></div>'; get_footer(); ?>
Note: If WordPress is installed in a subdirectory (like example.com/blog), update the path to $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php'.
2. Better Practice: Use a Custom Page Template
For front-facing pages, WordPress has a built-in system for custom templates that avoids manual core loading. Here's how to set it up:
- Create a file in your theme root (e.g.,
template-custom-page.php) - Add this template header comment at the top (WordPress uses this to recognize it as a template):
<?php /* Template Name: My Custom Page */ ?> - Now you can use template functions without any extra setup:
<?php get_header(); ?> <section class="custom-content"> <h1>This is my custom page, powered by WordPress!</h1> <!-- Add your HTML/PHP content here --> </section> <?php get_footer(); ?> - Head to your WordPress admin → Pages → Add New. On the right sidebar, find the "Template" dropdown and select "My Custom Page". Publish the page, and you're good to go—no more undefined function errors!
3. For Theme Function Files (Not Front Pages)
If your custom PHP file is for theme functionality (like adding custom shortcodes or hooks), don't load it directly. Instead, include it in your theme's functions.php file:
// In your theme's functions.php require_once(get_template_directory() . '/custom-functions.php');
This way, your file loads after WordPress is fully initialized, so all core functions are available right away.
内容的提问来源于stack exchange,提问作者sreehari mani

