WordPress開發(fā)中短代碼的實現(xiàn)及相關(guān)函數(shù)使用技巧
其實實現(xiàn)短代碼很簡單,我們只需要用到 WordPress 里面的一個函數(shù)就可以搞定短代碼,外加自己的一個小函數(shù),可以讓短代碼實現(xiàn)的輕松加愉快。
短代碼實現(xiàn)原理
就像往 WP 一些動作里加鉤子和過濾函數(shù)一樣,
短代碼只是經(jīng)過封裝了的針對文章輸出內(nèi)容的過濾器而已,
沒有像有一些主題功能說的那么震撼、那么高深。
下面來一個簡單例子:
function myName() {//短代碼要處理的函數(shù)
return "My name's XiangZi !";
}
//掛載短代碼
//xz為短代碼名稱
//即你在編輯文章時輸入[xz]就會執(zhí)行 myName 函數(shù)
add_shortcode('xz', 'myName');
那么我們在文章中輸入[xz]就會得到
My name's XiangZi !
短代碼傳參
更高深一點的利用,我將會在后面的文章中講到,
今天只講一下,短代碼的傳參機(jī)制
高級一點的例子
function myName($array,$content) {
var_dump($array);
var_dump($content);
}
add_shortcode('xz', 'myName');
編輯文章時我們輸入:
[xz a="1" b="2" c="3"]這里是三個參數(shù)哦[/xz]
在函數(shù)中我們將得到:
//$array 是一個數(shù)組,
//大體結(jié)構(gòu)如下
$array = array('a'=>'1','b'=>'2','c'=>'3');
//$content 是一個字符串
$content = '這里是三個參數(shù)哦';
shortcode_atts
不是因為搞短代碼插件,我也不會用到這個函數(shù),
shortcode_atts 函數(shù)主要是用來設(shè)置短代碼中截獲變量的初始值。
這是一個很實用的函數(shù),其實這個函數(shù)的真正是作用在數(shù)組上得,
因為我們從短代碼中截獲的參數(shù)都是數(shù)組形式的。
shortcode_atts 函數(shù)詳解
不要被函數(shù)名所疑惑,在 WordPress 里主要是用于設(shè)置短代碼參數(shù)的默認(rèn)值,
如果我們將代碼提取出來,用在別的地方,該函數(shù)可以幫我們設(shè)置一個既得數(shù)組的默認(rèn)值。
shortcode_atts 函數(shù)使用
這個函數(shù)使用起來很簡單。
shortcode_atts(array( "url" => 'http://PangBu.Com' ), $url)
以上代碼的意思是,
將 $url 數(shù)組 鍵值為url的成員默認(rèn)值設(shè)定為'http://PangBu.Com',
別的地方用處似乎不多,但對于一些超級懶人,有時候攬到總是忘記或是懶得設(shè)定數(shù)組的數(shù)值時,這個函數(shù)超好用。
shortcode_atts 函數(shù)聲明
/**
* 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;
}
相關(guān)文章
PHP仿tp實現(xiàn)mvc框架基本設(shè)計思路與實現(xiàn)方法分析
這篇文章主要介紹了PHP仿tp實現(xiàn)mvc框架基本設(shè)計思路與實現(xiàn)方法,簡單講述了php實現(xiàn)tp框架的原理,并結(jié)合實例形式分析了相關(guān)控制器、視圖及URL訪問操作技巧與注意事項,需要的朋友可以參考下2018-05-05
php通過array_unshift函數(shù)添加多個變量到數(shù)組前端的方法
這篇文章主要介紹了php通過array_unshift函數(shù)添加多個變量到數(shù)組前端的方法,涉及php中array_unshift函數(shù)操作數(shù)組的使用技巧,需要的朋友可以參考下2015-03-03
php采用file_get_contents代替使用curl實例
這篇文章主要介紹了php采用file_get_contents代替使用curl的方法,實例講述了file_get_contents模擬curl的post方法,對于服務(wù)器不支持curl的情況來說有一定的借鑒價值,需要的朋友可以參考下2014-11-11

