《PHP實戰:深入解析WordPress中加載模板的get_template_part函數》要點:
本文介紹了PHP實戰:深入解析WordPress中加載模板的get_template_part函數,希望對您有用。如果有疑問,可以聯系我們。
PHP實戰最近研究官方主題 Twenty Eleven ,有一些東西網上現成的中文資料欠好找,在博客里記載下來,算是分享,也算是備忘,wordpress 3.0 以后就開始便有了get_template_part() 這個函數 ,應該是為文章呈現形式提供更為多樣化的選擇而給出的新功能.
PHP實戰Twenty Eleven 中 實例如下:
PHP實戰Twenty Eleven index.php 文件
?行:21
PHP實戰
<?php if ( have_posts() ) : ?>
<?php twentyeleven_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop 在循環中使用以調用不同類型的文章 */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
............................
<?php endif; ?>
PHP實戰描述:
加載一個制定的模板到另一個模板里面(不同于包括header,sidebar,footer).
使得一個主題使用子模板來實現代碼段重用變得簡單
PHP實戰用于在模板中包括指定的模板文件,只需用指定參數slug和name就可以包括文件{slug}-{name}.php,最重要的功能是如果沒有這個文件就包括沒有{name}的.php文件文件
PHP實戰使用辦法:
PHP實戰
<?php get_template_part( $slug, $name ) ?>
PHP實戰參數:
PHP實戰示例:
PHP實戰使用 loop.php 在子主題里面
PHP實戰假設主題文件夾wp-content/themes下父主題是twentyten子主題twentytenchild,那么下面的代碼:
PHP實戰
<?php get_template_part( 'loop', 'index' ); ?>
PHP實戰php 的require()函數將按下面優先級包括文件
PHP實戰1. wp-content/themes/twentytenchild/loop-index.php
2. wp-content/themes/twentytenchild/loop.php
3. wp-content/themes/twentyten/loop-index.php
4. wp-content/themes/twentyten/loop.php
PHP實戰導航(這個例子很爛,但倒是另一種使用思路)
使用通用的nav.php文件給主題添加導航條:
PHP實戰
<?php get_template_part( 'nav' ); // Navigation bar (nav.php) ?>
<?php get_template_part( 'nav', '2' ); // Navigation bar #2 (nav-2.php) ?>
<?php get_template_part( 'nav', 'single' ); // Navigation bar to use in single pages (nav-single.php) ?>
PHP實戰get_template_part() 的鉤子詳解
因為在官方主題(Twenty Eleven)中 get_template_part() 函數被大量使用,所以就目前來看,該函數應該算是比較熱門的一個函數了,之前有寫過一篇文章講述該函數的具體使用辦法,在這里也就不便再贅述,本文主要針對該函數的 add_action 中的 hook $tag 值進行探討,因為,WP hook 中林林總總有那么些函數在$tag 值中比較讓人費解.
PHP實戰與普通hook的區別
普通的hook的$tag 是一個固定值,而 get_template_part() 確是一個可變值,好吧先不說,wp這么做給我們實現一個簡單功能帶來多少麻煩,但如此設置確實給多樣化的主題實現帶來了不少便利之處.
實現這一原理的源代碼如下,截取自 WordPress 源程序.
PHP實戰
function get_template_part( $slug, $name = null ) {
//$tag = "get_template_part_{$slug}"
//也便是,get_template_part_+你當時設置的$slug值
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
if ( isset($name) )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template($templates, true, false);
}
PHP實戰實例
像上面那樣說,可能也許基本上有點看不明白,好吧給點實例
PHP實戰?
PHP實戰
//溫習一下get_template_part($slug, $name)的用法,
//如果你在主題里這樣
get_template_part( 'index' , 'photo');
//那么 WP 會去找主題根目錄下 index-photo.php 文件
//那么我們想掛一個函數的話就得像如下
function addFunction ($slug, $name){
echo $slug;
}
add_action("get_template_part_index","addFunction",10,2);
PHP實戰get_template_part() 函數詳解備忘
《PHP實戰:深入解析WordPress中加載模板的get_template_part函數》是否對您有啟發,歡迎查看更多與《PHP實戰:深入解析WordPress中加載模板的get_template_part函數》相關教程,學精學透。維易PHP學院為您提供精彩教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/7740.html