在 WordPress 主題中增加自訂選項,通常會使用 WordPress 的主題自訂化 API(Theme Customization API)。這使你能夠在 WordPress 後台的「外觀 > 自訂」頁面中新增自訂選項,並在前台主題中應用這些選項。
以下是一個基本的步驟指南,介紹如何在你的 WordPress 主題中新增自訂選項:
1. 在主題的 functions.php 檔案中新增程式碼:
首先,打開你的 WordPress 主題的 functions.php 檔案,然後新增程式碼來註冊自訂選項。這通常涉及使用 add_theme_support() 函式來啟用主題自訂化 API,並註冊自訂選項。
function custom_theme_setup() {
add_theme_support('custom-logo'); // 範例:啟用自訂標誌圖像選項
add_theme_support('custom-header'); // 範例:啟用自訂頁首圖像選項
add_theme_support('custom-background'); // 範例:啟用自訂背景選項
}
add_action('after_setup_theme', 'custom_theme_setup');
2. 在主題中使用註冊的選項:
註冊選項後,你可以在主題模板中使用這些選項。例如,如果你啟用了自訂標誌圖像選項,可以在主題的適當位置使用以下程式碼來顯示標誌圖像:
if (function_exists('the_custom_logo')) {
the_custom_logo();
}
3. 在「外觀 > 自訂」頁面中新增選項:
啟用主題自訂化 API 後,你可以在 WordPress 後台的「外觀 > 自訂」頁面中看到新增的選項。你可以在主題的 functions.php 檔案中使用 add_action() 函式來新增自訂選項的控制面板。
function custom_theme_customizer($wp_customize) {
// 新增自訂選項到控制面板
$wp_customize->add_section('custom_section', array(
'title' => '自訂選項',
'priority' => 30,
));
$wp_customize->add_setting('custom_setting', array(
'default' => '',
));
$wp_customize->add_control('custom_control', array(
'label' => '自訂控制',
'section' => 'custom_section',
'settings' => 'custom_setting',
'type' => 'text',
));
}
add_action('customize_register', 'custom_theme_customizer');
在上述範例中,我們創建了一個名為 custom_section 的選項標籤,並在其中新增了一個文字輸入框,用於輸入自訂內容。