国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

深入解析WordPress中加載模板的get_template_part函數

2024-05-04 23:42:14
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了WordPress中加載模板的get_template_part函數,其中重點講解了其函數鉤子的使用,需要的朋友可以參考下
 

最近研究官方主題 Twenty Eleven ,有一些東西網上現成的中文資料不好找,在博客里記載下來,算是分享,也算是備忘,wordpress 3.0 以后就開始便有了get_template_part() 這個函數 ,應該是為文章呈現形式提供更為多樣化的選擇而給出的新功能。

Twenty Eleven 中 實例如下:

Twenty Eleven index.php 文件
 行:21

<?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; ?>

描述:
加載一個制定的模板到另一個模板里面(不同于包含header,sidebar,footer).
使得一個主題使用子模板來實現代碼段重用變得簡單

用于在模板中包含指定的模板文件,只需用指定參數slug和name就可以包含文件{slug}-{name}.php,最重要的功能是如果沒有這個文件就包含沒有{name}的.php文件文件

使用方法:

<?php get_template_part( $slug, $name ) ?>

參數:

  • $slug (必須) 通用的模板名
  • $name (可選) 指定的模板名

示例:

使用 loop.php 在子主題里面

假設主題文件夾wp-content/themes下父主題是twentyten子主題twentytenchild,那么下面的代碼:

<?php get_template_part( 'loop', 'index' ); ?>

php 的require()函數將按下面優先級包含文件

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

導航(這個例子很爛,但卻是另一種使用思路)
使用通用的nav.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) ?>

get_template_part() 的鉤子詳解
因為在官方主題(Twenty Eleven)中 get_template_part() 函數被大量使用,所以就目前來看,該函數應該算是比較熱門的一個函數了,之前有寫過一篇文章講述該函數的具體使用方法,在這里也就不便再贅述,本文主要針對該函數的 add_action 中的 hook $tag 值進行探討,因為,WP hook 中林林總總有那么些函數在$tag 值中比較讓人費解。

與普通hook的區別
普通的hook的$tag 是一個固定值,而 get_template_part() 確是一個可變值,好吧先不說,wp這么做給我們實現一個簡單功能帶來多少麻煩,但如此設置確實給多樣化的主題實現帶來了不少方便之處。
實現這一原理的源代碼如下,截取自 WordPress 源程序。

 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);}

實例
像上面那樣說,可能也許基本上有點看不明白,好吧給點實例

 

//復習一下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);

get_template_part() 函數詳解備忘



注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 太仓市| 塘沽区| 会泽县| 道孚县| 长沙市| 龙泉市| 东明县| 玉树县| 盐城市| 滕州市| 荔浦县| 黎平县| 张北县| 贞丰县| 信丰县| 保德县| 子长县| 松滋市| 元江| 蕲春县| 邢台县| 鹰潭市| 离岛区| 大连市| 舞阳县| 浏阳市| 朝阳县| 巨鹿县| 拉孜县| 登封市| 张北县| 平南县| 孟连| 特克斯县| 平泉县| 双鸭山市| 电白县| 衡南县| 孝义市| 陆丰市| 双鸭山市|