《PHP應(yīng)用:WordPress開發(fā)中短代碼的實(shí)現(xiàn)及相關(guān)函數(shù)使用技巧》要點(diǎn):
本文介紹了PHP應(yīng)用:WordPress開發(fā)中短代碼的實(shí)現(xiàn)及相關(guān)函數(shù)使用技巧,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
PHP應(yīng)用其實(shí)實(shí)現(xiàn)短代碼很簡(jiǎn)單,我們只需要用到 WordPress 里面的一個(gè)函數(shù)就可以搞定短代碼,外加本身的一個(gè)小函數(shù),可以讓短代碼實(shí)現(xiàn)的輕松加愉快.
PHP應(yīng)用短代碼實(shí)現(xiàn)原理
就像往 WP 一些動(dòng)作里加鉤子和過濾函數(shù)一樣,
短代碼只是經(jīng)過封裝了的針對(duì)文章輸出內(nèi)容的過濾器罷了,
沒有像有一些主題功能說的那么震撼、那么高深.
下面來一個(gè)簡(jiǎn)單例子:
PHP應(yīng)用
function myName() {//短代碼要處理的函數(shù)
return "My name's XiangZi !";
}
//掛載短代碼
//xz為短代碼名稱
//即你在編纂文章時(shí)輸入[xz]就會(huì)執(zhí)行 myName 函數(shù)
add_shortcode('xz', 'myName');
PHP應(yīng)用那么我們?cè)谖恼轮休斎隱xz]就會(huì)得到
PHP應(yīng)用
My name's XiangZi !
PHP應(yīng)用短代碼傳參
更高深一點(diǎn)的利用,我將會(huì)在后面的文章中講到,
本日只講一下,短代碼的傳參機(jī)制
高級(jí)一點(diǎn)的例子
PHP應(yīng)用
function myName($array,$content) {
var_dump($array);
var_dump($content);
}
add_shortcode('xz', 'myName');
PHP應(yīng)用編纂文章時(shí)我們輸入:
PHP應(yīng)用
[xz a="1" b="2" c="3"]這里是三個(gè)參數(shù)哦[/xz]
PHP應(yīng)用在函數(shù)中我們將獲得:
PHP應(yīng)用
//$array 是一個(gè)數(shù)組,
//大體布局如下
$array = array('a'=>'1','b'=>'2','c'=>'3');
//$content 是一個(gè)字符串
$content = '這里是三個(gè)參數(shù)哦';
PHP應(yīng)用shortcode_atts
不是因?yàn)楦愣檀a插件,我也不會(huì)用到這個(gè)函數(shù),
shortcode_atts 函數(shù)主要是用來設(shè)置短代碼中截獲變量的初始值.
這是一個(gè)很實(shí)用的函數(shù),其實(shí)這個(gè)函數(shù)的真正是作用在數(shù)組上得,
因?yàn)槲覀儚亩檀a中截獲的參數(shù)都是數(shù)組形式的.
PHP應(yīng)用shortcode_atts 函數(shù)詳解
不要被函數(shù)名所疑惑,在 WordPress 里主要是用于設(shè)置短代碼參數(shù)的默認(rèn)值,
如果我們將代碼提取出來,用在其余地方,該函數(shù)可以幫我們?cè)O(shè)置一個(gè)既得數(shù)組的默認(rèn)值.
PHP利用shortcode_atts 函數(shù)使用
這個(gè)函數(shù)使用起來很簡(jiǎn)單.
PHP應(yīng)用
shortcode_atts(array(
"url" => 'http://PangBu.Com'
), $url)
PHP應(yīng)用以上代碼的意思是,
將 $url 數(shù)組 鍵值為url的成員默認(rèn)值設(shè)定為'http://PangBu.Com',
其余地方用處似乎不多,但對(duì)于一些超級(jí)懶人,有時(shí)候攬到總是忘記或是懶得設(shè)定數(shù)組的數(shù)值時(shí),這個(gè)函數(shù)超好用.
PHP利用shortcode_atts 函數(shù)聲明
PHP利用
/**
* Combine user attributes with known attributes and fill in defaults when needed.
*
* The pairs should be considered to be all of the attributes which are
* supported by the caller and given as a list. The returned attributes will
* only contain the attributes in the $pairs list.
*
* If the $atts list has unsupported attributes, then they will be ignored and
* removed from the final returned list.
*
* @since 2.5
*
* @param array $pairs Entire list of supported attributes and their defaults.
* @param array $atts User defined attributes in shortcode tag.
* @return array Combined and filtered attribute list.
*/
function shortcode_atts($pairs, $atts) {
$atts = (array)$atts;
$out = array();
foreach($pairs as $name => $default) {
if ( array_key_exists($name, $atts) )
$out[$name] = $atts[$name];
else
$out[$name] = $default;
}
return $out;
}
歡迎參與《PHP應(yīng)用:WordPress開發(fā)中短代碼的實(shí)現(xiàn)及相關(guān)函數(shù)使用技巧》討論,分享您的想法,維易PHP學(xué)院為您提供專業(yè)教程。
轉(zhuǎn)載請(qǐng)注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/7903.html