本章以「商品列表外掛」作為整合專案,把 CPT、自訂欄位、資料儲存與前台列表串起來。完成後你會具備開發小型內容管理外掛的實務雛形。
本章學習目標
能規劃商品資料結構,儲存自訂欄位,並用 shortcode 或模板顯示商品列表。
15.1 商品列表外掛的規劃及設計
商品列表至少需要商品名稱、描述、價格、圖片與狀態。若只是展示商品,可用 CPT 加自訂欄位;若要購物車、付款與訂單,應評估 WooCommerce 等成熟方案。
資料欄位規劃
- 商品名稱:使用 CPT 標題。
- 商品描述:使用內容編輯器。
- 商品圖片:使用精選圖片。
- 價格與 SKU:使用 post meta。
- 商品分類:使用 taxonomy。
15.2 儲存自訂資料
自訂欄位可透過 meta box 或區塊編輯器側欄建立。儲存時要檢查 nonce、權限與自動儲存狀態。
function wp2026_save_product_meta($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (!current_user_can('edit_post', $post_id)) return;
$price = isset($_POST['wp2026_price']) ? sanitize_text_field(wp_unslash($_POST['wp2026_price'])) : '';
update_post_meta($post_id, '_wp2026_price', $price);
}
資料驗證
價格應檢查是否為數字,網址應使用 esc_url_raw(),純文字使用 sanitize_text_field()。儲存前清理,輸出前仍要轉義。
15.3 顯示商品列表
前台可用 shortcode 顯示商品列表,讓管理者可以把列表放到任意頁面。
add_shortcode('wp2026_products', 'wp2026_products_shortcode');
function wp2026_products_shortcode() {
$query = new WP_Query(['post_type' => 'product', 'posts_per_page' => 12]);
ob_start();
if ($query->have_posts()) {
echo '<div class="product-grid">';
while ($query->have_posts()) {
$query->the_post();
echo '<article class="product-card">';
the_title('<h3>', '</h3>');
echo esc_html(get_post_meta(get_the_ID(), '_wp2026_price', true));
echo '</article>';
}
echo '</div>';
}
wp_reset_postdata();
return ob_get_clean();
}
本章練習
- 建立 product CPT。
- 新增價格自訂欄位。
- 建立
[wp2026_products]短代碼。 - 用 CSS 設計商品卡片列表。