短代碼 類似論壇 BBCode,在文章內容中用 [tag] 形式調用 PHP 函數輸出動態內容。支援:自閉合、包裹內容、屬性傳遞。
| 類型 | 範例 |
|---|---|
| 無屬性自閉合 | [year] |
| 包裹內容 | [note]提示文字[/note] |
| 帶屬性 | [button url="https://a.com" color="red"]點我[/button] |
| 單屬性簡寫 | [video "mp4"] |
function bing_shortcode_year() {
return date('Y');
}
add_shortcode('year', 'bing_shortcode_year');
function bing_shortcode_handler($atts, $content = '') {
// $atts: 關聯陣列 ['url'=>'...', 'color'=>'...']
// $content: 包裹內容字串(自閉合時為 '')
}
add_shortcode('tag', 'bing_shortcode_handler');
function bing_btn($atts, $content) {
$atts = shortcode_atts([
'url' => '#',
'color' => 'blue',
'text' => '按鈕'
], $atts, 'btn'); // 第三參數為短代碼名,用於 filter 短代碼屬性
return '<a href="'.esc_url($atts['url']).'" class="btn btn-'.$atts['color'].'">'.$atts['text'].'</a>';
}
add_shortcode('btn', 'bing_btn');
remove_shortcode('year'); // 移除單個
remove_all_shortcodes(); // 移除所有
shortcode_exists('year'); // bool 是否已註冊
has_shortcode($content, 'year'); // bool 內容中是否包含
echo do_shortcode('[year]'); // 手動執行並獲取輸出
function bing_map_shortcode($atts, $content) {
$GLOBALS['bing_map_loaded'] = true; // 標記
return '<div id="map"></div>';
}
add_shortcode('map', 'bing_map_shortcode');
function bing_map_scripts() {
if (!empty($GLOBALS['bing_map_loaded'])) {
wp_enqueue_script('map-api', 'https://maps.googleapis.com/...', [], null, true);
}
}
add_action('wp_footer', 'bing_map_scripts'); // 頁腳輸出,確保短代碼已跑過
WordPress 核心不支援巢狀同名短代碼。若需巢狀,內層需用不同名稱或手動 do_shortcode($content):
function bing_outer($atts, $content) {
return '<div class="outer">'.do_shortcode($content).'</div>';
}
add_shortcode('outer', 'bing_outer');
短代碼開發核心:add_shortcode 註冊 → 回調處理 $atts/$content → shortcode_atts 合併預設值 → 返回 HTML。善用 do_shortcode 處理巢狀、wp_footer 按需加載腳本,保持頁面輕量。