撰寫一個簡單的短碼功能
	短碼功能的目的是可以在靜態的頁面或文章中加入一個短碼,這個短碼對應到一個函式,你可以想像成可在頁面或文章中呼叫一個預先寫好的函式,在頁面或文章插入短碼處得到該函式回傳的結果字串,這個字串可以是一個簡單的數字、文字、一段HTML碼…,於是,一個頁面或文章就能夠從靜態內容的特性變成具有動態內容的特性。
以下的範例,我們直接虛擬主機後台檔案管理建立外掛,另外一種建立外掛是在本地端寫好外掛,打包成壓縮檔,上傳並安裝外掛,啟用外掛…。
在WordPress裏的wp-content->plugins所有外掛資料夾中建立tbare-wordpress-plugin-demo目錄:
 在資料夾裏建立一個新的檔案:tbare-wordpress-plugin-demo.php
 
在資料夾裏建立一個新的檔案:tbare-wordpress-plugin-demo.php
 輸入以下程式碼:
輸入以下程式碼:
 到後台啟用所寫的外掛
 
到後台啟用所寫的外掛
 
在頁面編輯中,插入短碼:[tbare-plugin-demo]
 頁面顯示:
 
頁面顯示:
 檢視產出的原始碼:
檢視產出的原始碼:
	
 在資料夾裏建立一個新的檔案:tbare-wordpress-plugin-demo.php
 
在資料夾裏建立一個新的檔案:tbare-wordpress-plugin-demo.php
 輸入以下程式碼:
輸入以下程式碼:
<?php
/**
 * Plugin Name: TBare Wodpress Plugin demo
 * Plugin URI: https://www.tbare.com
 * Description: Display content using a shortcode to insert in a page or post
 * Version: 0.1
 * Text Domain: tbare-wordpress-plugin-demo
 * Author: Tim Bare
 * Author URI: https://www.tbare.com
 */
 
 function tbare_wordpress_plugin_demo($atts) {
  $Content = "<style>rn";
  $Content .= "h3.demoClass {rn";
  $Content .= "color: #26b158;rn";
  $Content .= "}rn";
  $Content .= "</style>rn";
  $Content .= '<h3 class="demoClass">Check it out!</h3>';
   
    return $Content;
}
add_shortcode('tbare-plugin-demo', 'tbare_wordpress_plugin_demo');
 
 到後台啟用所寫的外掛
 
到後台啟用所寫的外掛
 頁面顯示:
 
頁面顯示:
 檢視產出的原始碼:
檢視產出的原始碼:
<style>
h3.demoClass {
color: #26b158;
}
</style>
<h3 class="demoClass">Check it out!</h3>
 
參考資源:
- Create a simple WordPress Plugin with Shortcode
- Getting Started with WordPress Shortcodes & Sample Snippets
- How to Add a Shortcode in WordPress? (Beginner’s Guide)
- WordPress Shortcodes: A Complete Guide
- How To Use WordPress do_shortcode
- How to Use Shortcode in WordPress PHP Theme File Templates
- The Beginner’s Guide to Writing Your Own Custom Shortcode
- The Ultimate Guide to WordPress Shortcodes (With Examples to Create Your Own)
- The Complete Guide to Creating Custom Shortcodes in WordPress

