Shortcode(簡碼)是 WordPress 內容擴展的利器,類似 BBCode,讓編輯器無代碼嵌入複雜功能。本文系統講解註冊、屬性、巢狀、移除、判斷、執行、條件載入資源等全流程。
[shortcode] // 自閉合 [shortcode]內容[/shortcode] // 閉合,含內容 [shortcode attr="value" attr2="val"] // 帶屬性 [shortcode "value"] // 單屬性簡寫
add_shortcode('tag', 'callback_function');
tag:Shortcode 名稱(小寫、無空格、建議加前綴避免衝突)callback:回調函數,接收兩參數 ($atts, $content)function my_hello_shortcode($atts, $content) {
return 'Hello World!';
}
add_shortcode('hello', 'my_hello_shortcode');
文章中輸入 [hello] → 前台顯示 Hello World!。
shortcode_atts() 設定預設值function my_link_shortcode($atts, $content) {
$atts = shortcode_atts([
'url' => 'https://example.com',
'text' => '點擊訪問',
'blank' => false,
], $atts, 'my_link'); // 第三參數為 filter 鉤子名
$target = $atts['blank'] ? ' target="_blank"' : '';
return '' . esc_html($atts['text']) . '';
}
add_shortcode('my_link', 'my_link_shortcode');
shortcode_atts():合併用戶屬性與預設值,並觸發 shortcode_atts_{$shortcode} 過濾器供其他插件修改預設值。extract() 可解包陣列為變數,但現代風格建議直接 $atts['key'] 存取。[my_link url="https://wordpress.org" text="WP 官網" blank="true"]
remove_shortcode('hello'); // 移除單個
remove_all_shortcodes(); // 移除所有(慎用,影響核心/其他插件)
if (shortcode_exists('hello')) { ... } // 全域是否註冊
$content = '測試 [hello] 內容';
if (has_shortcode($content, 'hello')) { ... } // 特定字串是否包含
do_shortcode()$content = '歡迎 [hello] 來到本站'; echo do_shortcode($content); // 歡迎 Hello World! 來到本站
核心已掛載:add_filter('the_content', 'do_shortcode', 11);,文章內容自動處理。
痛點:Shortcode 需要特定資源,但全站載入浪費頻寬。
// 1. Shortcode 回調中設定全域標記
function my_map_shortcode($atts, $content) {
$GLOBALS['my_map_shortcode_used'] = true;
return '';
}
add_shortcode('google_map', 'my_map_shortcode');
// 2. wp_footer 中判斷標記再掛載資源
function my_map_enqueue_scripts() {
if (!empty($GLOBALS['my_map_shortcode_used'])) {
wp_enqueue_script('google-maps-api', 'https://maps.googleapis.com/maps/api/js?key=YOUR_KEY');
wp_enqueue_script('my-map-init', get_template_directory_uri() . '/js/map-init.js', ['google-maps-api'], null, true);
wp_enqueue_style('my-map-style', get_template_directory_uri() . '/css/map.css');
}
}
add_action('wp_footer', 'my_map_enqueue_scripts');
the_content 過濾器(優先級 11),早於 wp_footer(優先級 20),故全域標記已就緒。核心不支援直接巢狀,需在父 Shortcode 中手動遞歸處理:
function parent_shortcode($atts, $content) {
$content = do_shortcode($content); // 遞歸處理內層
return '' . $content . '';
}
wp-includes/shortcodes.php:所有 Shortcode API 實現add_shortcode() + 回調 ($atts, $content)shortcode_atts() 設定預設值 + 過濾器擴展remove_shortcode/shortcode_exists/has_shortcode/do_shortcodewp_footer 延遲掛載do_shortcode($content)esc_url()/esc_html()/esc_attr()