get_template_part()?函數用于調用自定義模板文件,也可以引入自定義名字的文件。
使用get_template_part()函數,可以更靈活的控制主題,我覺得get_template_part()函數最大的好處就是大大的減少了代碼的重寫量。
我們知道,調用header.php可以用get_header()方法,調用footer.php可以用get_footer()方法,調用 sidebar.php可以用get_sidebar()方法,那么,調用自定義模板文件的時候,我們需要用get_template_part()函 數。
這好比如比如原生的php就有require及include兩種引入文件方法一個道理。
為什么要自定義模板文件?
比如,分類頁、標簽頁、作者頁、甚至首頁可能都需要用到一段共同的代碼——以摘要方式輸出文章。那么,我們可以將這段代碼放到content.php中,然后在分類、標簽、作者和首頁模板文件調用content.php,以減少代碼重寫量。
get_template_part()函數用法
get_template_part()函數的使用很靈活,不僅僅是加載一個模板文件進來,而且還有備用的選項,調用代碼如下:
get_template_part( $slug, $name );
參數:
$slug?
(必須) 通用的模板名
(字符串)要引入的模板的文件名,不包括后綴名 .php,也就是如果需要引入當前主題根目錄的 loop.php 文件 $slug 填寫 “loop” 即可。
$name
?(可選) 指定的模板名
(字符串)要引入的模板的文件的副文件名,如果要引入當前主題根目錄的 loop-img.php 文件 $slug 參數填寫 “loop”,$name 參數填寫 “img”。
示例
1、如果content-loop.php存在,則調用content-loop.php,否則,就調用content.php
get_template_part( 'content', 'loop' );
2、引入當前主題根目錄的 tags.php文件:
get_template_part( 'tags' );
3、引入當前主題 inc 目錄的 myfunctions.php 文件:
get_template_part( 'inc/myfunctions' );
4、調用主題partials文件夾下content-page.php
php get_template_part( 'partials/content', 'page' );
?
源文件
get_template_part() 位于 wp-includes/general-template.php.
推薦:
get_post_format();
獲取帖子格式
根據返回的格式調用指定的模板文件
get_template_part('slug',get_post_format());
get_template_part():根據get_post_format()返回的信息來加載slug開頭命名的相應的模板;
get_post_format():獲取當前post的分類信息。
例子:
現有模板 content-image.php
那么
get_template_part('content',get_post_format());
?
如果當前post分類是image,那么就會調用模板content-image.php;如果返回的post分類模板不存在,那么就會使用默認post模板。