wordpress主题的后台Settings API 和 Theme Customizer API开发部分

先看两个概念Settings APITheme Customizer API

Settings API和Theme Customizer API是WordPress提供的用于处理主题和插件设置的工具。它们分别用于不同的场景和目的,但都旨在简化在WordPress仪表板中添加设置和选项的过程。

Settings API

Settings API主要用于创建和管理WordPress仪表板中的设置页面。它提供了一种用于注册设置、添加设置区域和设置字段的方法,使开发人员能够轻松地向主题或插件中添加配置选项。

其关键的函数和概念

  • register_setting:
    用于注册设置,指定设置名称、选项组和一个用于对输入数据进行清理的回调函数。

  • add_settings_section:
    用于在设置页面上添加一个区域,将设置字段组织成逻辑部分。

  • add_settings_field:
    用于在设置页面上添加一个字段,例如文本输入框、复选框等。

例如:

function theme_settings_init() {
    
    
    register_setting('theme_options', 'theme_options', 'theme_options_sanitize');
    add_settings_section('general_settings', 'General Settings', 'general_settings_callback', 'theme-options');
    add_settings_field('custom_text_field', 'Custom Text Field', 'custom_text_field_callback', 'theme-options', 'general_settings');
}
add_action('admin_init', 'theme_settings_init');

Theme Customizer API

Theme Customizer API则允许用户在实时预览中调整主题设置。它提供了一个用户友好的界面,使用户能够直观地定制主题的外观和功能。

关键的函数和概念:

  • add_section:
    用于在定制器中添加一个新的部分,将相关设置组织在一起。

  • add_setting:
    用于添加一个设置,指定设置的名称、默认值和一个用于清理和验证输入的回调函数。

  • add_control:
    用于添加一个控件,用户可以通过它输入或选择值

function theme_customizer_settings($wp_customize) {
    
    
    $wp_customize->add_section('custom_text_section', array(
        'title' => 'Custom Text Section',
        'priority' => 30,
    ));

    $wp_customize->add_setting('custom_text_setting', array(
        'default' => '',
        'sanitize_callback' => 'sanitize_text_field',
    ));

    $wp_customize->add_control('custom_text_setting', array(
        'label' => 'Custom Text Setting',
        'section' => 'custom_text_section',
        'type' => 'text',
    ));
}
add_action('customize_register', 'theme_customizer_settings');

区别和用途

Settings API:
用于在WordPress仪表板中的“外观” -> “主题选项”下创建设置页面。
主要用于静态页面,用户需要保存设置后才能看到效果。
适用于那些不需要实时预览的设置。

Theme Customizer API:
用于实现实时主题定制,用户可以在定制器中直接预览并调整设置。
适用于需要实时反馈的设置,用户无需保存设置即可看到变化。
提供了更直观的用户体验,允许用户在实时中查看并调整主题的外观。

猜你喜欢

转载自blog.csdn.net/weixin_45047825/article/details/134691995
今日推荐