WordPress開發(fā)函數(shù)add_shortcode()
WordPress開發(fā)函數(shù)add_shortcode(),添加一個新的短碼。
用法:
add_shortcode( string $tag, callable $callback )
描述:
應該注意通過前綴或其他方法來確保所添加的shortcode標簽是唯一的,不會與其他已經添加的shortcode標簽沖突。在重復標記的情況下,最后加載的標記將優(yōu)先。
參數(shù):
$tag
(string) (必需) Shortcode標簽要在帖子內容中搜索。
$callback
(callable) (必需) 找到短代碼時要運行的回調函數(shù)。默認情況下,每個shortcode回調函數(shù)被傳遞三個參數(shù),包括一個屬性數(shù)組($atts), shortcode內容,如果沒有設置則為null ($content),最后是shortcode標簽本身($shortcode_tag),按照這個順序。
更多信息
shortcode回調函數(shù)將被傳遞三個參數(shù):shortcode屬性、shortcode內容(如果有的話)和shortcode的名稱。
每個短代碼只能有一個鉤子。這意味著如果另一個插件有類似的短代碼,它會覆蓋你的,或者你的插件會覆蓋他們的,這取決于插件被包含和/或運行的順序。
Shortcode屬性名稱在傳遞給處理程序函數(shù)之前總是轉換為小寫。值是不變的。
請注意,shortcode調用的函數(shù)不應該產生任何類型的輸出。Shortcode函數(shù)應該返回用于替換Shortcode的文本。直接產生輸出將會導致意想不到的結果。這類似于篩選器函數(shù)的行為方式,因為它們不應該從調用中產生預期的副作用,因為您無法控制從何時何地調用它們。
來源:
文件: wp-includes/shortcodes.php
function add_shortcode( $tag, $callback ) {
global $shortcode_tags;
if ( '' === trim( $tag ) ) {
$message = __( 'Invalid shortcode name: Empty name given.' );
_doing_it_wrong( __FUNCTION__, $message, '4.4.0' );
return;
}
if ( 0 !== preg_match( '@[<>&/[]x00-x20=]@', $tag ) ) {
/* translators: 1: Shortcode name, 2: Space-separated list of reserved characters. */
$message = sprintf( __( 'Invalid shortcode name: %1$s. Do not use spaces or reserved characters: %2$s' ), $tag, '& / < > [ ] =' );
_doing_it_wrong( __FUNCTION__, $message, '4.4.0' );
return;
}
$shortcode_tags[ $tag ] = $callback;
}
更新日志:

用戶貢獻的筆記
(由Codex - 6年前貢獻)
例子
使用API的一個簡單的短代碼標簽示例:[footag foo="bar"]
add_shortcode( 'footag', 'wpdocs_footag_func' );
function wpdocs_footag_func( $atts ) {
return "foo = {$atts['foo']}";
}
一個很好的屬性默認值的例子: [bartag foo="bar"]
add_shortcode( 'bartag', 'wpdocs_bartag_func' );
function wpdocs_bartag_func( $atts ) {
$atts = shortcode_atts( array(
'foo' => 'no foo',
'baz' => 'default baz'
), $atts, 'bartag' );
return "foo = {$atts['foo']}";
}
包含內容的示例:[baztag]content[/baztag]
add_shortcode( 'baztag', 'wpdocs_baztag_func' );
function wpdocs_baztag_func( $atts, $content = "" ) {
return "content = $content";
}
如果你的插件被設計成一個類,可以這樣寫:
add_shortcode( 'baztag', array( 'MyPlugin', 'wpdocs_baztag_func' ) );
class MyPlugin {
public static function wpdocs_baztag_func( $atts, $content = "" ) {
return "content = $content";
}
}
(由dingo-d - 1年前貢獻)
當在插件中添加' add_shortcode() '函數(shù)時,最好將其添加到' init '掛鉤的函數(shù)中。這樣wordpress就有時間進行正確的初始化。
add_action( 'init', 'wpdocs_add_custom_shortcode' );
function wpdocs_add_custom_shortcode() {
add_shortcode( 'footag', 'wpdocs_footag_func' );
}
正如插件手冊中描述的那樣。
(由Patrick Johanneson貢獻- 3年前)
注釋(來自法典- https://codex.wordpress.org/Function_Reference/add_shortcode#Notes)
- shortcode回調函數(shù)將被傳遞三個參數(shù):shortcode屬性、shortcode內容(如果有的話)和shortcode的名稱。
- 每個短代碼只能有一個鉤子。這意味著如果另一個插件有類似的短代碼,它將覆蓋你的或你的將覆蓋他們的取決于插件的順序被包含和/或運行。
- Shortcode屬性名稱在傳遞給處理程序函數(shù)之前總是轉換為小寫。值是不變的。
- 請注意,shortcode調用的函數(shù)不應該產生任何類型的輸出。Shortcode函數(shù)應該返回用于替換Shortcode的文本。直接產生輸出將會導致意想不到的結果。這類似于篩選器函數(shù)的行為方式,因為它們不應該從調用中產生預期的副作用,因為您無法控制從何時何地調用它們。