Wordpress内置主题选项
制作一款高级的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';
参考文档:
The Customize API
WordPress Theme Panel Options Frameworks
Creating WordPress Theme Options With the Theme Customization API