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

首頁 > 開發 > PHP > 正文

WordPress開發中短代碼的實現及相關函數使用技巧

2024-05-04 23:41:56
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了WordPress開發中短代碼的實現及相關函數使用技巧,文中講到了add_shortcode函數和shortcode_atts函數的用法,需要的朋友可以參考下
 

其實實現短代碼很簡單,我們只需要用到 WordPress 里面的一個函數就可以搞定短代碼,外加自己的一個小函數,可以讓短代碼實現的輕松加愉快。

短代碼實現原理
就像往 WP 一些動作里加鉤子和過濾函數一樣,
短代碼只是經過封裝了的針對文章輸出內容的過濾器而已,
沒有像有一些主題功能說的那么震撼、那么高深。
下面來一個簡單例子:

function myName() {//短代碼要處理的函數return "My name's XiangZi !";}//掛載短代碼//xz為短代碼名稱 //即你在編輯文章時輸入[xz]就會執行 myName 函數add_shortcode('xz', 'myName');

那么我們在文章中輸入[xz]就會得到

My name's XiangZi !

短代碼傳參
更高深一點的利用,我將會在后面的文章中講到,
今天只講一下,短代碼的傳參機制
高級一點的例子

function myName($array,$content) {var_dump($array);var_dump($content);} add_shortcode('xz', 'myName');

編輯文章時我們輸入:

[xz a="1" b="2" c="3"]這里是三個參數哦[/xz]

在函數中我們將得到:

//$array 是一個數組,//大體結構如下$array = array('a'=>'1','b'=>'2','c'=>'3');//$content 是一個字符串$content = '這里是三個參數哦';

shortcode_atts
不是因為搞短代碼插件,我也不會用到這個函數,
shortcode_atts 函數主要是用來設置短代碼中截獲變量的初始值。
這是一個很實用的函數,其實這個函數的真正是作用在數組上得,
因為我們從短代碼中截獲的參數都是數組形式的。

shortcode_atts 函數詳解
不要被函數名所疑惑,在 WordPress 里主要是用于設置短代碼參數的默認值,
如果我們將代碼提取出來,用在別的地方,該函數可以幫我們設置一個既得數組的默認值。

shortcode_atts 函數使用
這個函數使用起來很簡單。

shortcode_atts(array("url" => 'http://PangBu.Com'), $url)

以上代碼的意思是,
將 $url 數組 鍵值為url的成員默認值設定為'http://PangBu.Com',
別的地方用處似乎不多,但對于一些超級懶人,有時候攬到總是忘記或是懶得設定數組的數值時,這個函數超好用。

shortcode_atts 函數聲明

/** * 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教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 广昌县| 西和县| 永年县| 泌阳县| 当雄县| 青冈县| 中宁县| 右玉县| 咸丰县| 嘉禾县| 车险| 洪泽县| 沁源县| 宣恩县| 太仓市| 阳新县| 西乡县| 岑巩县| 嘉禾县| 大城县| 荔浦县| 高唐县| 庆安县| 上虞市| 宜宾市| 涟水县| 黄梅县| 盐亭县| 泾阳县| 威信县| 德惠市| 靖安县| 博罗县| 井研县| 舞钢市| 奉节县| 齐河县| 佛山市| 晋江市| 洛南县| 朝阳县|