WordPress 簡碼是一種類似於論壇標籤的東西,格式類似於把尖括號換成中括號的 Html 標籤。簡碼很多人叫做短程式碼,但官方的翻譯應該是簡碼,在這裡糾正一下。
簡碼的開發的邏輯比較簡單,主要就是新增、刪除和判斷,會在本文全部介紹。
簡碼格式
簡碼的格式非常靈活,可以是有屬性、無屬性、閉合、非閉合等等:
[example]
[example] 內容 [/example]
[example attr="屬性" attr-hide="1"] 內容 [/example]
[example "屬性"]
新增簡碼
新增簡碼需要使用 add_shortcode() 函式,兩個屬性,第一個為簡碼名,第二個是簡碼的回撥函式。
|
1 |
add_shortcode($tag,$func); |
例如新增名為 test 的簡碼,回撥 Bing_shortcode_test() 函式:
|
functionBing_shortcode_test($attr,$content){ return'Hello World!'; } add_shortcode('test','Bing_shortcode_test'); |
在文章中新增 [test] 就會輸出 「Hello World!」 。
從上邊的例子可以看到,簡碼的回撥函式需要接收兩個引數。第一個是簡碼所有的屬性,透過陣列儲存;第二個是簡碼的內容 (閉合簡碼中的內容) 。
移除簡碼
remove_shortcode() 函式可以移除一個簡碼,只需要指定簡碼的名稱即可移除。
|
1 |
remove_shortcode('test'); |
remove_all_shortcodes() 函式用來移除當前新增的所有簡碼。
|
1 |
remove_all_shortcodes(); |
判斷簡碼
關於判斷簡碼,有兩個函式,shortcode_exists() 函式判斷簡碼是否存在。
|
remove_all_shortcodes(); if(shortcode_exists('test'))echo'簡碼 test 存在';//False add_shortcode('test','Bing_shortcode_test'); if(shortcode_exists('test'))echo'簡碼 test 存在';//True |
還有一個 has_shortcode() 函式,判斷字串中是否出現某某簡碼。
|
$content='測試測試測試測試測試測試測試測試'; if(has_shortcode($content,'test'))echo'字串中有 test 簡碼';//False $content='測試測試測試測 [test] 測試 [/test] 試測試測試測試測試'; if(has_shortcode($content,'test'))echo'字串中有 test 簡碼';//True |
執行簡碼
do_shortcode() 函式用來在字串中查詢簡碼,並在簡碼處呼叫之前新增的回撥函式,把簡碼執行成需要的內容。
WordPress 新增的鉤子:
|
1 |
add_filter('the_content','do_shortcode',11); |
例子:
|
functionBing_shortcode_test($attr,$content){ return'Hello World!'; } add_shortcode('test','Bing_shortcode_test'); $content='測試測試測試測 [test] 試測試測試測試測試'; echodo_shortcode($content);//測試測試測試測 Hello World! 試測試測試測試測試 |
簡碼屬性
簡碼支援各種格式的屬性,接受給簡碼回撥函式的第一個引數。如果你要給引數設定預設值,可以使用 shortcode_atts() 函式:
|
functionBing_shortcode_test($attr,$content){ extract(shortcode_atts(array( 'url'=>'http://www.bgbk.org', 'hide'=>false, 'text'=>'點選隱藏 / 顯示' ),$attr)); $hide=$hide?' style="display:none;"':''; return'<a href="http://'/spanspan./spanspan$url/spanspan./spanspan'"'.$hide.'>'.$text.'</a>'; } add_shortcode('test','Bing_shortcode_test'); |
總結
簡碼是個非常強大的功能,對文章內容是一種很好的擴充套件,利用好可以讓新增某些東西變的方便快捷。
關於簡碼的函式都在:wp-includes/shortcode.php 檔案裡,有能力的朋友可以閱讀一下,瞭解原理。
更多關於簡碼使用技巧的文章:https://www.weixiaoduo.com/tag/shortcode