1. 創建外掛目錄和主文件

wp-content/plugins/ 目錄下創建一個新的目錄,例如 custom-category-display,然後在該目錄中創建外掛的主文件 custom-category-display.php,並在該文件中定義外掛的基本訊息。

/*
Plugin Name: Custom Category Display
Description: A plugin to display selected categories on the frontend.
Version: 1.0
Author: Your Name
*/

// Your plugin code here

 

2. 添加設定頁面

custom-category-display.php 中,使用 add_submenu_page() 函式來添加一個設定頁面。

function custom_category_display_settings_page() {
    // 顯示設定頁面的內容
}

function custom_category_display_menu() {
    add_submenu_page(
        'options-general.php',
        'Custom Category Display',
        'Custom Category Display',
        'manage_options',
        'custom-category-display',
        'custom_category_display_settings_page'
    );
}
add_action('admin_menu', 'custom_category_display_menu');

 

3. 在設定頁面中添加多選的 checkbox

function custom_category_display_settings_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    // 取得所有分類
    $categories = get_categories();

    // 取得使用者選擇的分類
    $selected_categories = get_option('selected_categories', array());
    // 顯示多選的 checkbox
    echo '<form action="options.php" method="post">';
    settings_fields('custom-category-display');
    echo '<h2>選擇要輪播的分類</h2>';
    foreach ($categories as $category) {
        echo '<label>';
        echo '<input type="checkbox" name="selected_categories[]" value="' . esc_attr($category->term_id) . '" ' . checked(in_array($category->term_id, $selected_categories), true, false) . '>';
        echo esc_html($category->name);
        echo '</label><br>';
    }
    submit_button();
    echo '</form>';
}

 

4. 保存選擇的分類

admin_init 操作中,使用 register_setting() 函式來註冊設定,並處理和更新選擇的分類。

function custom_category_display_init() {
    register_setting(
        'custom-category-display',
        'selected_categories',
        array('sanitize_callback' => 'custom_category_sanitize_selected_categories')
    );
}
add_action('admin_init', 'custom_category_display_init');

// 自訂的過濾函式,處理選擇的分類 ID
function custom_category_sanitize_selected_categories($input) {
    if (is_array($input)) {
        // 將每個值轉換為正整數
        return array_map('absint', $input);
    }
    return array();
}

 

這樣設定完成之後,就可以在後台的 dashboard 側欄設定的地方,看到這個 plugin 了。

 

5. 前台顯示

在前台顯示儲存後的分類,你需要在前端的模板文件中使用適當的程式碼來檢索並顯示已儲存的分類。以下是如何在前台顯示儲存後的分類的一般步驟:

在你的模板文件中,使用 get_option() 函式來獲取儲存的分類選項。

$selected_categories = get_option('selected_categories', array());

之後就可以透過取得的分類陣列,去把對應的資訊取出來了。