首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

WordPress 短代碼 開發完整指南

     編輯:PHP 綜合知識

什麼是短代碼?

短代碼 類似論壇 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');

七、Gutenberg 區塊 vs 短代碼

  • Gutenberg 區塊:現代化、可視化編輯、儲存為註釋 + HTML
  • 短代碼:輕量、相容舊編輯器、適合簡單動態插入
  • 建議:新功能優先開發區塊,舊專案維護短代碼即可

總結

短代碼開發核心:add_shortcode 註冊 → 回調處理 $atts/$content → shortcode_atts 合併預設值 → 返回 HTML。善用 do_shortcode 處理巢狀、wp_footer 按需加載腳本,保持頁面輕量。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved