WordPress函数:get_template_part 加载模板模块文件

江河/ 2023年04月22日/ WordPress/ 浏览 1039

函数原型:


get_template_part( string $slug, string $name = null, array $args = array() ): void|false


为子主题提供一种简单的机制,以重载主题中可重用的代码部分。


包含主题的命名模板零件,或者如果指定了名称,则将包含特定的模块。如果主题不包含{slug}.php文件,那么将不包含任何模板。


该模板是使用require包含的,而不是require_one包含的,因此您可以多次包含同一个模板部分。


对于$name参数,如果文件名为“{slug}-special.php”,则应指定 $name 为:“special”。


参数说明:


$slug,模板的 $slug,比如模板文件 header.php 的$slug 是 'header',footer.php 的$slug 是 'footer'。


$name,指定特定的模板模块。比如上文提到的 {slug}-special.php 中 $name 为:“special”。


$args,传递给模板文件的参数。


函数源码:


function get_template_part( $slug, $name = null, $args = array() ) {
	do_action( "get_template_part_{$slug}", $slug, $name, $args );

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

	$templates[] = "{$slug}.php";

	do_action( 'get_template_part', $slug, $name, $templates, $args );

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


包含钩子:


do_action( 'get_template_part', string $slug, string $name, string[] $templates, array $args )

do_action( "get_template_part_{$slug}", string $slug, string|null $name, array $args )


使用举例:


get_template_part(
	'template-part',
	'name',
	array(
		'key'	=> 'value',
		'key2'	=> 'value2'
	)
);


发表评论

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

客服 工单