在WordPress中,get_header()
和 get_footer()
是两个非常常用的模板函数,它们用于包含主题的头部(header)和底部(footer)文件。以下是这两个函数的基本使用方法:
1. 使用 get_header()
get_header()
函数用于在主题的模板文件中包含头部文件。通常,这个函数会在主题的header.php
文件中调用。
使用方法:
在你的主题的任何模板文件(例如 index.php
, single.php
, page.php
等)中,你可以在文件的最顶部添加以下代码:
<?php
get_header();
?>
这行代码告诉WordPress包含当前主题目录下的header.php
文件。如果你需要包含一个特定的头部文件,你也可以传递一个参数来指定文件名,例如:
<?php
get_header('custom-header');
?>
这将尝试包含名为custom-header.php
的文件。
2. 使用 get_footer()
get_footer()
函数用于在主题的模板文件中包含底部文件。通常,这个函数会在主题的footer.php
文件中调用。
使用方法:
在你的主题的任何模板文件中,你可以在文件的最底部添加以下代码:
<?php
get_footer();
?>
这行代码告诉WordPress包含当前主题目录下的footer.php
文件。同样地,如果你需要包含一个特定的底部文件,你可以传递一个参数来指定文件名,例如:
<?php
get_footer('custom-footer');
?>
这将尝试包含名为custom-footer.php
的文件。
示例
以下是一个简单的WordPress模板文件示例,展示了如何在模板中使用 get_header()
和 get_footer()
:
<?php
/**
* Template Name: Custom Page Template
*/
get_header(); // Include the header.php file ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<!-- Your content goes here -->
</main>
</div>
<?php get_footer(); // Include the footer.php file ?>
在这个示例中,get_header()
在内容区域之前被调用,而 get_footer()
在内容区域之后被调用。这确保了在页面的正确位置包含了头部和底部。