制作一款高级的WordPress主题集成强大的主题选项面板是必不可少的,常见的主题选项框架有:Redux Framework、Options Framework、Fluent Framework等,前两个用的比较多。
其实还有一个就是WordPress内置的,WordPress很早就集成主题选项API,预置了几乎你能想到所有设置选项,最大的优势是可以实时预览设置的内容,这是上面的主题选项框架做不到的。
下面的是个简单的示例,将代码添加到主题函数模板functions.php中即可:
展开收缩
function zm_customize_register($wp_customize) {
$wp_customize->add_setting('header_title', array(
'default' => '默认文字',
'capability' => 'edit_theme_options',
'sanitize_callback' => 'sanitize_header_title'
));
$wp_customize->add_setting('header_subtitle');
$wp_customize->add_setting('intro_text');
$wp_customize->add_setting('featured_post');
$wp_customize->add_section('zm_general_section', [
'title' => '主题设置',
'priority' => 1
]);
$wp_customize->add_control('zm_header_title_ctrl', [
'label' => 'Header Title',
'section' => 'zm_general_section',
'settings' => 'header_title',
'type' => 'text'
]);
$wp_customize->add_control('zm_header_subtitle_ctrl', [
'label' => 'Header Subtitle',
'section' => 'zm_general_section',
'settings' => 'header_subtitle',
'type' => 'text'
]);
$wp_customize->add_control('zm_intro_text_ctrl', [
'label' => 'Intro Text',
'section' => 'zm_general_section',
'settings' => 'intro_text',
'type' => 'textarea'
]);
$pages = get_posts([
'nopaging' => true,
'post_type' => 'page',
'post_status' => 'publish'
]);
$page_ids = array_map(function($el) {
return $el->ID;
}, $pages);
$page_names = array_map(function ($el) {
return $el->post_title;
}, $pages);
$wp_customize->add_control('zm_featured_post_ctrl', [
'label' => 'Featured Post',
'section' => 'zm_general_section',
'settings' => 'featured_post',
'type' => 'select',
'choices' => array('' => '') + array_combine($page_ids, $page_names)
]);
}
add_action('customize_register', 'zm_customize_register');
function sanitize_header_title($title) {
return ucfirst($title);
}调用方法:
echo get_theme_mod('header_title');上面只是基本的设置,如果想添加更多的设置选项,可以参考官方文档。
或者下载使用完整的选项文件。
解压后将文件夹放到主题目录中,调用方式:
require get_template_directory() . '/theme-customizer-demo.php';
更多:
https://github.com/search?q=wordpress-theme-customizer-custom-controls
https://github.com/search?q=wordpress-customizer-custom-controls&type=Repositories
参考文档:
WordPress Theme Panel Options Frameworks
Creating WordPress Theme Options With the Theme Customization API
本站文章大部分为原创,用于个人学习记录,可能对您有所帮助,仅供参考!

我的微信
微信号已复制
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!







1F
虽然我不会用,但是我还是过来看看
2F
我猜测这个是给主题发布分享站点使用的,可以让自己或访客自由选用网站主题。