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