WordPress主题:get_header、get_footer与include、require的区别

追格官方小助手/ 2023年02月17日/ WordPress/ 浏览 2074

WordPress 主题页面的结构,比较常见就像下面的示例:


<?php get_header(); ?>
<h2>Error 404 - Not Found</h2>
<?php get_sidebar(); ?>
<?php get_footer(); ?>


这些 get_header、get_sidebar、get_footer,看上去就是把 header.php,footer.php,sidebar.php 包含进了文件,和 include、require的功能差不多。既然封装成新的函数,估计还是有点不一样的。


看下函数 get_footer 的源代码:


function get_footer( $name = null, $args = array() ) {
	/**
	 * Fires before the footer template file is loaded.
	 *
	 * @since 2.1.0
	 * @since 2.8.0 The `$name` parameter was added.
	 * @since 5.5.0 The `$args` parameter was added.
	 *
	 * @param string|null $name Name of the specific footer file to use. Null for the default footer.
	 * @param array       $args Additional arguments passed to the footer template.
	 */
	do_action( 'get_footer', $name, $args );

	$templates = array();
	$name      = (string) $name;
	if ( '' !== $name ) {
		$templates[] = "footer-{$name}.php";
	}

	$templates[] = 'footer.php';

	if ( ! locate_template( $templates, true, true, $args ) ) {
		return false;
	}
}


代码做了三件事:调用 get_footer 钩子,就是埋了个点;根据$name判断,调用不同的php文件;调用 locate_template 函数。


再看WordPress文档中关于 locate_template 的介绍:


在TEMPLATEPATH和wpincludes/theme-compat之前的STYLESHEETPATH中进行搜索,以便从父主题继承的主题只能重载一个文件。


原来子主题的实现,需要依赖 locate_template 函数。


如果直接使用 include、 require 而不是 使用 get_header,get_footer 等函数,就会破坏子主题机制。


发表评论

暂无评论,抢个沙发...

客服 工单