使用 WordPress 主题定制 API

原文来自:http://ju.outofmemory.cn/entry/193049

前言:如果不是主题制作者或折腾爱好者,以下功能可以直接改主题 css 就可实现。

主题定制API是什么?

后台 – 外观 – 自定义,默认主题“Twenty Fifteen”支持“颜色、顶部图像、背景图形、小工具”等设置,而且改动时所见即所得,也叫“即时预览(Live Preview)”。

之前,想给主题用户提供一些自定义选项,比较常见的是增加一个“主题设置页”,用户改动好后得保存下然后刷新页面看效果。之之前,WordPress 提供了自定义头部和背景图片的设置,在外观设置中有个独立页面,能上传图片裁剪等设置。如今,使用这个“主题定制API(Theme_Customization_API )”可以直接在类似侧边栏中设置并即时预览。

说明:WordPress 3.4 开始默认支持“站点标题和副标题”和“静态首页”的设置,其它设置项都需要主题内相应的函数支持。

理解此 API 的三要素:Section 、Setting 和 Control

  • Section 是每一个设置区域的“标题”。
  • Setting 是每一个区域内具体的设置选项。
  • Control 是对每一个选项进行设置。

下面让我们一起来个创建“顶部背景”,增加对主题“顶部背景颜色”和“顶部背景图片”的支持。

function mytheme_customize_register( $wp_customize ) {
    //三要素是添加到这里的,都挂在 customize_register
}
add_action( 'customize_register', 'mytheme_customize_register' );

创建一个 Section

使用 $wp_customize->add_section 来创建,定义此 section 为“header_bg”,以及显示的标题和位置。

    $wp_customize->add_section('header_bg',array(
        'title'     => '顶部背景',
        'priority'  => 50
    ) );

priority 设定此 section 的位置序列。默认 section 的 ID 有: title_tagline, colors, header_image, background_image, nav and static_front_page,相应的标题和位置序列如图:

  • title_tagline – Site Title & Tagline (网站标题和描述)
  • colors – Colors(颜色)
  • header_image – Header Image (顶部图片)
  • background_image – Background Image (背景图片)
  • nav – Navigation (导航菜单)
  • static_front_page – Static Front Page (静态首页)

添加两个 Setting

使用 $wp_customize->add_setting 来添加,定义两个 setting 为 “header_bg_color”和“header_bg_image”。

    $wp_customize->add_setting( 'header_bg_color', array(
        'default'   => '#515865',
        "transport" => "postMessage",
        'type'      => 'option'
    ) );
    $wp_customize->add_setting( 'header_bg_image', array(
        'default'   => '',
        "transport" => "postMessage",
        'type'      => 'option'
    ) );

transport 两个值:refresh 或 postMessage,需要即时预览果断后者。

添加对应 Control

使用 $wp_customize->add_control 来添加,包括之前代码完整如下:

function mytheme_customize_register( $wp_customize ) {
    $wp_customize->add_section('header_bg',array(
        'title'     => '顶部背景',
        'priority'  => 50
    ) );
    $wp_customize->add_setting( 'header_bg_color', array(
        'default'   => '#515865',
        'transport' => 'postMessage',
        'type'      => 'option'
    ) );
    $wp_customize->add_setting( 'header_bg_image', array(
        'default'   => '',
        'transport' => 'postMessage',
        'type'      => 'option'
    ) );
    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'header_bg_color', array(
         'label'     => '顶部背景颜色',
        'section'   => 'header_bg'
    ) ) );
    $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'header_bg_image', array(
         'label'     => '顶部背景图片',
         'section'   => 'header_bg'
    ) ) );
}
add_action( 'customize_register', 'mytheme_customize_register' );
  • WP_Customize_Color_Control() – 创建一个从色轮中选择颜色的颜色选择器
  • WP_Customize_Image_Control() – 创建上传图片或从媒体库中选择图片的控件
  • WP_Customize_Control() – 创建一个输入纯文本的控件
  • WP_Customize_Upload_Control() – 创建上传媒体文件的控件
  • WP_Customize_Background_Image_Control() – 创建背景图片选择器
  • WP_Customize_Header_Image_Control() – 创建顶部背景图片选择器

生效样式

把样式挂载到 wp_head 来生效。

function mytheme_customize_css(){
    $hbc = get_option('header_bg_color','#515865');
    $hbi = get_option('header_bg_image');
?>
<style type="text/css">
    #header{
        background-color:<?php echo $hbc;?>;
        <?php echo empty($hbi)? '' : 'background-image:url(' .$hbi.');' ;?>
}
</style>
<?php
}
add_action( 'wp_head', 'mytheme_customize_css');

现在,你能在页面源码上查看到已设定的样式加载在 <head> 。当然 #head 的根据自己的主题模板进行修改。

说明:如果 setting 里的 type 未设定为 option,则使用: get_theme_mod 来调用。

即时预览

新建个 js 文件,丢入如下代码(#header 需修改):

( function( $ ) {
    api = wp.customize;
    api( 'header_bg_color', function( value ) {
        value.bind( function( newval ) {
            $('#header').css('background-color', newval );
        } );
    } );
    api( 'header_bg_image', function( value ) {
        value.bind( function( newval ) {
 === $.trim( newval ).length ?
            $( '#header' ).css( 'background-image', '' ) :
            $( '#header' ).css( 'background-image', 'url( ' + newval + ')' );
        } );
    } );
} )( jQuery );

把这个 customizer.js 丢如主题 js 文件夹内。

function mytheme_customizer_live_preview(){
    wp_enqueue_script('mytheme-customizer',get_template_directory_uri().'/js/customizer.js',array( 'jquery','customize-preview' ),'',true);
}
add_action( 'customize_preview_init', 'mytheme_customizer_live_preview' );

Over 来得那么突然!

简单回顾下,主要用三个钩子:

function mytheme_customize_register( $wp_customize ) {
    //三要素
}
add_action( 'customize_register', 'mytheme_customize_register' );
function mytheme_customize_css(){
    //生效样式
}
add_action( 'wp_head', 'mytheme_customize_css');
function mytheme_customizer_live_preview(){
    //加载“即时预览”的 js
    wp_enqueue_script('mytheme-customizer',get_template_directory_uri().'/js/customizer.js',array( 'jquery','customize-preview' ),'',true);
}
add_action( 'customize_preview_init', 'mytheme_customizer_live_preview' );

附:三要素各详细属性:

$wp_customize->add_section( 'id', array(
    'title' => '',
    'description' => '',
    'priority' => ''
) );
 
$wp_customize->add_setting( 'id', array(
    'default' => '',
    'theme-supports' => '',
    'type' => '', // Default is "theme_mod"
    'capability' => '', // Default is "edit_theme_options"
    'sanitize_callback' => '',
    'sanitize_js_callback => '',
    'transport' => '', // Default is "refresh",or use "postMessage"
) );
 
$wp_customize->add_control( 'id', array(
    'label' => '',
    'settings' =>  // Default is id property.
    'section' => '',
    'type' => '', // Default is "text",or use "checkbok、radio(choices)、select、dropbown-pages、"
    'choices' => '', // This is optional, depending on type's value.
    'priority' => '', // Default is 10.
) );

参考资料:

Getting Started with the WordPress Theme Customization API :简单明了,结构清晰,推荐。

A Guide to the WordPress Theme Customizer :系列教程非常强大。