在 WordPress 主题中,你可以通过以下几种方式引用模板文件:
1. 包含主题文件
使用 get_template_part()函数,这是最推荐的方法:
<?php get_template_part('content', 'single'); ?>
// 会按顺序查找:content-single.php → content.php
2. 包含子主题文件
如果你的主题支持子主题,使用 get_stylesheet_directory():
<?php get_template_part(get_stylesheet_directory() . '/template-parts/header'); ?>
3. 使用 include 或 require
直接包含文件路径:
<?php
// 包含主题目录下的文件
include(get_template_directory() . '/template-parts/content.php');
// 或者使用 locate_template() 更安全
include(locate_template('template-parts/content.php'));
?>
4. 条件包含模板
根据条件包含不同的模板:
<?php
if (is_front_page()) {
get_template_part('template-parts/content', 'frontpage');
} elseif (is_single()) {
get_template_part('template-parts/content', 'single');
} else {
get_template_part('template-parts/content');
}
?>
5. 在 functions.php 中加载模板文件
通过钩子加载:
add_action('wp_head', 'custom_template_part');
function custom_template_part() {
if (is_single()) {
get_template_part('template-parts/custom', 'header');
}
}
6. 通过短代码加载
创建短代码来包含模板:
// functions.php
add_shortcode('my_template', 'load_my_template');
function load_my_template($atts) {
ob_start();
get_template_part('template-parts/my', 'template');
return ob_get_clean();
}
// 在文章或页面中使用
// [my_template]
7. 主题文件结构示例
推荐的目录结构:
your-theme/
├── header.php
├── footer.php
├── index.php
├── single.php
├── page.php
└── template-parts/
├── content.php
├── content-single.php
├── content-page.php
├── header/
│ ├── site-header.php
│ └── site-navigation.php
└── footer/
├── site-footer.php
└── widgets.php
8. 传递变量到模板
如果需要传递变量:
<?php
$args = array(
'title' => 'Hello World',
'content' => 'This is some content'
);
set_query_var('template_args', $args);
get_template_part('template-parts/card', 'component');
// 在 template-parts/card-component.php 中
$args = get_query_var('template_args');
echo $args['title'];
?>
最佳实践建议:
- 使用
get_template_part() – 支持子主题覆盖 - 合理组织目录结构 – 将模板部件放在
template-parts/目录 - 使用有意义的命名 – 如
content-{post-type}.php - 考虑性能 – 避免在循环中多次包含大文件
- 遵循 WordPress 模板层级 – 让 WordPress 自动选择最合适的模板
选择哪种方法取决于你的具体需求,但 get_template_part()通常是首选,因为它支持子主题覆盖并且更符合 WordPress 标准。


湘公网安备43020002000238