- 赤色のリンクは、まだ日本語Codexに存在しないページ・画像です。英語版と併せてご覧ください。(詳細)
テーマカスタマイズ API
目次
はじめに
For more up-to-date, detailed information about the Customizer API, please see the new official documentation in the theme handbook: https://developer.wordpress.org/themes/advanced-topics/customizer-api/.
WordPress 3.4で追加されたテーマカスタマイズ API は、「外観 → カスタマイズ」画面を開発者がカスタマイズしたりコントロールを追加できるようにします。 テーマカスタマイズ画面(つまり "テーマカスタマイザー")ではサイト管理者がテーマ設定や色調、ウィジェットを変更したり、これらの変更をリアルタイムでプレビューできます。
ここではテーマカスタマイズ API と、テーマ内での実装方法を説明します。
この記事は、あなたが WordPress のテーマやプラグイン作成について説明しているテーマの作成、プラグインの作成を読んでいることを前提としています。また、オブジェクト指向プログラミングについての理解も必要です。WordPress の Settings_API に精通しているなら、より理解しやすいでしょう。
注意: この情報は WordPress バージョン 3.4以降のものです。
カスタマイザーの作成
テーマまたはプラグイン開発者のいずれも、よりパワフルでインタラクティブなカスタマイズ設定をテーマやプラグインに加えることができます。
カスタマイズ設定を加えるには少なくとも2つのフックを使います。
-
customize_register
/ en - カスタマイザー画面用のセクション、テーマ設定、コントロールを定義します。
-
wp_head
- テーマ設定の変更をライブプレビューするためのCSS を出力します。
注意: テーマカスタマイザー画面で JavaScript をエンキューするために customize_preview_init
フックを使うことも可能です。JavaScript でテーマカスタマイザーをよりレンスポンスよくパワフルにできますが、このステップは必須ではありません。
重要: Do not conditionally load your Customizer code with an is_admin()
check. If you only add your customize_register
if is_admin()
, then any panels, sections, or controls will be unavailable when the Customizer preview loads. As of WordPress 4.1, there are contextual panels, sections, and controls so that they can be displayed only on certain URLs being previewed. If you only register your panels, sections, and controls if is_admin()
then you'll be effectively saying that these are not contextual to any URL on your site. For more information, see #30387 and #29758.
パート1: テーマ設定、コントロールの定義など
テーマ設定、セクション、コントロールはすべて customize_register
/ en アクションで追加します。このアクションは WP_Customize_Manager
/ en クラスのインスタンスである $wp_customize
オブジェクトが引数になります。
まず以下のようにアクションを定義します:
function mytheme_customize_register( $wp_customize ) { // セクション、テーマ設定、コントロールを追加します。 } add_action( 'customize_register', 'mytheme_customize_register' );
$wp_customize
オブジェクトが関数の引数として渡されます。テーマカスタマイズ画面に作成したテーマ設定はすべてこの $wp_customize
オブジェクトのメソッドで実行されます。
次にテーマ設定、セクション、コントロールを追加します。コントロールが機能するにはセクションとセッティングが1つずつ必要です。
テーマ設定の追加
テーマ設定は WordPress の theme_mod の仕組みを使って値の取得/設定を行います。
テーマカスタマイザーにテーマ設定を追加するには、$wp_customize->add_setting()
/ en メソッドを使います。これにより、他に何もしなくてもテーマ設定の追加、保存、取得が可能になります。
customize_register
アクションでセッティングを新規追加する例:
$wp_customize->add_setting( 'header_textcolor' , array( 'default' => '#000000', 'transport' => 'refresh', 'sanitize_callback' => 'header_textcolor_validate', ) );
注意: transport
パラメータは任意でデフォルト値は 'refresh'
です。デフォルトのままなら、テーマ設定が変更された時にプレビューウインドウ自体が表示の更新をして設定を反映します。
煩雑な更新を避けてレスポンスを良くしたい場合は 'postMessage'
を指定します。
これは JavaScript でスタイルの更新を反映します(後述のライブプレビュー設定のセクションを参照)。
セクションの追加
セクションはテーマ設定のグループです。コントロールを追加するときにセクションを追加する必要があります。新しいセクションを追加せずに、既存のセクションにコントロールを追加することも_できます_。
テーマカスタマイザーにセクションを追加するには $wp_customize->add_section()
/ en メソッドを使います。
customize_register
アクションでセクションを追加する例:
$wp_customize->add_section( 'mytheme_new_section_name' , array( 'title' => __( 'Visible Section Name', 'mytheme' ), 'priority' => 30, ) );
WordPress にはビルトインセクションがあります。これらを使う場合は add_section()
せずに、セクション名を指定します。ビルトインセクションには以下のものがあります。
- title_tagline - サイトタイトルとキャッチフレーズ
- colors - 色
- header_image - ヘッダー画像
- background_image - 背景画像
- nav - ナビゲーション(訳注:無いかも?)
- static_front_page - 固定フロントページ
コントロールの追加
コントロールはテーマカスタマイザー画面に表示されるフォームの入力要素です。 これでテーマ設定を変更し、リアルタイムに変更をプレビューします。各コントロールは1つのセッティングと1つのセクションに紐づけられます。
コントロールを追加するには $wp_customize->add_control()
/ en メソッドを使います。
customize_register
アクションでコントロールをセクションに追加する例:
$wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'link_color', array( 'label' => __( 'Header Color', 'mytheme' ), 'section' => 'your_section_id', 'settings' => 'your_setting_id', ) ) );
コントロールは他のクラス(例では WP_Customize_Color_Control()
/ en クラス)に渡すためのオプションを持ちます。他の例は $wp_customize->add_control()
/ en を参照してください。
パート2: ライブCSSの生成
テーマ設定を取得し、ヘッダーにCSSを出力します。
上記のように customize_register
アクションでテーマ設定を追加したなら、wp_head
アクションで CSS を出力したり、get_theme_mod() / en で設定値を取得するだけです。
For example, let's say you have a setting called 'header_color' and it looks like this:
$wp_customize->add_setting( 'header_color' , array( 'default' => '#000000', 'transport' => 'refresh', ) );
Your code to output the css into the header might look something like this:
function mytheme_customize_css() { ?> <style type="text/css"> h1 { color:<?php echo get_theme_mod('header_color', '#000000'); ?>; } </style> <?php } add_action( 'wp_head', 'mytheme_customize_css');
When you look at the page source you would see the following in the header:
<style type="text/css"> h1 {color:#000000;} </style>
You will notice that the default value of #000000 is given for the color. Once this value is changed via the customizer, the new value will be shown. For example, let's say you wanted to change the color to white. In the customizer, you insert the hex value for white, #ffffff, click Save and Publish.
Now in the page source you will see:
<style type="text/css"> .h1 {color:#ffffff;} </style>
テーマ設定でパート1 の 'transport'=>'postMessage'
を明示的に指定していない限りテーマカスタマイズ設定は自動で更新されます。
ヒント:このチュートリアルの最後にサンプルテーマカスタマイズクラスがあります。このクラスの generate_css()
という便利な関数(WordPress の関数ではありません)で簡単に CSS を出力することができます。
パート3: ライブプレビュー設定(任意)
このステップは必須ではありませんが、ユーザー体験を劇的に改善できます。 通常はプレビューウインドウの再読み込みにより設定を反映しますが、JavaScript を使うことでより速い、インタラクティブなテーマカスタマイザーを実現できます。
JavaScript のハンドラを作るためには以下が必要です:
1. テーマ設定をすべて 'transport'=>'postMessage'
と指定します。
2. ライブな変更を反映するための JavaScript ファイル(例 theme-customize.js)を作ります。
3. 2の js ファイルをエンキューするために customize_preview_init / en をフックします。
各ステップを説明します。
ステップ 1: テーマ設定の更新
まず、テーマ設定で 'transport'=>'postMessage'
と指定します(上記「テーマ設定の追加」参照)。これでテーマ設定の変更時にプレビューの自動更新が行われなくなり、JavaScript での反映が可能になります。
WordPress のテーマカスタマイザー設定はすべてデフォルトで 'transport'=>'refresh'
です。これを変更するには 'customize_register'
フックで以下のように記述します:
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; $wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage'; $wp_customize->get_setting( 'background_color' )->transport = 'postMessage';
ステップ 2: JavaScript ファイルの作成
次にプレビューを制御するための新しい JavaScript ファイルを作成します。通常はファイル名を theme-customizer.js としテーマフォルダ内の js フォルダに置きますが、制限はありません。
theme-customizer.js ファイルには以下のように書きます:
/** * このファイルはテーマカスタマイザーライブプレビューをライブにします。 * テーマ設定で 'postMessage' を指定し、ここで制御します。 * JavaScript はコントロールからテーマ設定を取得し、 * jQuery を使ってページに変更を反映します。 */ ( function( $ ) {
// リアルタイムにサイトタイトルを変更 wp.customize( 'blogname', function( value ) { value.bind( function( newval ) { $( '#site-title a' ).html( newval ); } ); } );
// リアルタイムにキャッチフレーズを変更 wp.customize( 'blogdescription', function( value ) { value.bind( function( newval ) { $( '.site-description' ).html( newval ); } ); } ); // リアルタイムにサイトタイトルの色を変更 wp.customize( 'header_textcolor', function( value ) { value.bind( function( newval ) { $('#site-title a').css('color', newval ); } ); } ); // リアルタイムに背景色を変更 wp.customize( 'background_color', function( value ) { value.bind( function( newval ) { $('body').css('background-color', newval ); } ); } ); // リアルタイムにリンク色を変更 wp.customize( 'mytheme_options[link_textcolor]', function( value ) { value.bind( function( newval ) { $('a').css('color', newval ); } ); } ); } )( jQuery );
このコードからわかるように、一つのテーマ設定に対して以下のように書きます。
wp.customize( 'YOUR_SETTING_ID', function( value ) { value.bind( function( newval ) { // なんかする(newval 変数が新しい設定値を持っています) } ); } );
ステップ 3: JavaScript のエンキュー
JavaScript をエンキューします。
(公開画面側ではなく)テーマカスタマイザー管理画面でのみファイルを読み込むには customize_preview_init / en フックを使います。
/** * 実行されるフック: 'customize_preview_init' * * @see add_action('customize_preview_init',$func) */ public static function mytheme_customizer_live_preview() { wp_enqueue_script( 'mytheme-themecustomizer', //このスクリプトの ID 名 get_template_directory_uri().'/assets/js/theme-customizer.js', // このファイルの URL array( 'jquery','customize-preview' ), // 必須の依存ファイル , // このスクリプトのバージョン(任意) true // フッターに出力する場合 true にします ); } add_action( 'customize_preview_init', 'mytheme_customizer_live_preview' );
サンプルテーマカスタマイズクラス
既存テーマに簡単に組み込めるテーマカスタマイズクラスの例です。 このクラスは前述の theme-customize.js ファイル内で使用します。
<?php /** * テーマカスタマイズ画面のカスタマイズ * * @link http://codex.wordpress.org/Theme_Customization_API * @since MyTheme 1.0 */ class MyTheme_Customize { /** * このフックは WP3.4から利用可能な 'customize_register' をフックし、 * テーマカスタマイズ画面に新しいセクションとコントロールを追加します。 * * 注意:即時反映するには JavaScript を書く必要があります。 * 詳しくは live_preview() を参照。 * * @see add_action('customize_register',$func) * @param \WP_Customize_Manager $wp_customize * @link http://ottopress.com/2012/how-to-leverage-the-theme-customizer-in-your-own-themes/ * @since MyTheme 1.0 */ public static function register ( $wp_customize ) { //1. (必要なら)テーマカスタマイザー上に新しいセクションを追加します。 $wp_customize->add_section( 'mytheme_options', array( 'title' => __( 'MyTheme Options', 'mytheme' ), //セクションのタイトル 'priority' => 35, //セクションの表示順序 'capability' => 'edit_theme_options', //権限 'description' => __('Allows you to customize some example settings for MyTheme.', 'mytheme'), //ツールチップ表示内容 ) ); //2. WPデータベースに新しいテーマ設定を追加します。 $wp_customize->add_setting( 'mytheme_options[link_textcolor]', //シリアライズしたテーマ設定名 (すべての設定はDBの1レコードに格納されます) array( 'default' => '#2BA6CB', //デフォルト値 'type' => 'option', //'option' または 'theme_mod' 'capability' => 'edit_theme_options', //(任意)アクセス権限 'transport' => 'postMessage', //テーマ設定値更新のトリガー。'refresh' または 'postMessage'(即時反映) ) ); //3. コントロール(テーマ設定をセクションに紐づけてフォームコントロールを出力します)を追加します。 $wp_customize->add_control( new WP_Customize_Color_Control( //カラーコントロールクラスを生成します $wp_customize, // (必須)$wp_customize オブジェクト 'mytheme_link_textcolor', //コントロールの ID属性値 array( 'label' => __( 'Link Color', 'mytheme' ), //管理画面に表示するコントロール名 'section' => 'colors', //このコントロールを出力するセクションのID名(追加したものか、ビルトインセクション) 'settings' => 'mytheme_options[link_textcolor]', //シリアライズしたテーマ設定名 'priority' => 10, //セクション内での表示順序 ) ) ); //4. JavaScript で即時反映するために、ビルトインテーマ設定の transport 指定を変更することもできます。 $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; $wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage'; $wp_customize->get_setting( 'background_color' )->transport = 'postMessage'; } /** * ライブプレビュー中の <head> 内に CSS を出力します。 * * 実行されるフック: 'wp_head' * * @see add_action('wp_head',$func) * @since MyTheme 1.0 */ public static function header_output() { ?> <style type="text/css"> <?php self::generate_css('#site-title a', 'color', 'header_textcolor', '#'); ?> <?php self::generate_css('body', 'background-color', 'background_color', '#'); ?> <?php self::generate_css('a', 'color', 'link_textcolor'); ?> </style> <?php } /** * 即時反映のための JavaScript をエンキューします。 * この関数はテーマ設定で 'transport'=>'postMessage' を指定した場合のみ必要です。 * * 実行されるフック: 'customize_preview_init' * * @see add_action('customize_preview_init',$func) * @since MyTheme 1.0 */ public static function live_preview() { wp_enqueue_script( 'mytheme-themecustomizer', // Give the script a unique ID get_template_directory_uri() . '/assets/js/theme-customizer.js', // Define the path to the JS file array( 'jquery', 'customize-preview' ), // Define dependencies , // Define a version (optional) rue // Specify whether to put in footer (leave this true) ); } /** * <head> 内に出力する CSS を作成します。 * $mod_name 設定が未定義の場合は、何も出力しません。 * * @uses get_theme_mod() * @param string $selector CSSセレクタ。 * @param string $style 変更する CSS *プロパティ* 名。 * @param string $mod_name 'theme_mod' 設定の名前。 * @param string $prefix (任意)CSS プロパティの前に出力する内容。 * @param string $postfix (任意)CSS プロパティの後に出力する内容。 * @param bool $echo (任意)出力するか否か (デフォルト:true)。 * @return string セレクタとプロパティからなる1行の CSS を返します。 * @since MyTheme 1.0 */ public static function generate_css( $selector, $style, $mod_name, $prefix=, $postfix=, $echo=true) { $return = ; $mod = get_theme_mod($mod_name); if ( ! empty( $mod ) ) { $return = sprintf('%s { %s:%s; }', $selector, $style, $prefix.$mod.$postfix ); if ( $echo ) { echo $return; } } return $return; } } // テーマ設定やコントロールをセットアップします。 add_action( 'customize_register' , array( 'MyTheme_Customize' , 'register' ) ); // ライブプレビュー中のサイトに CSS を出力します。 add_action( 'wp_head' , array( 'MyTheme_Customize' , 'header_output' ) ); // 即時反映用の JavaScript をエンキューします。 add_action( 'customize_preview_init' , array( 'MyTheme_Customize' , 'live_preview' ) );
外部資料
- Otto's Theme Customization Tutorial
- Using panels and active callbacks in Customizer
- Comprehensive Guide to make WordPress Theme Options with Customization API by NARGA
- Digging Into the Theme Customizer: Overview
- Example Solution with documented source
- Theme Customization snippets
- Slides about the Customizer
- A collection of custom controls you can use in your WordPress theme customizer page
関連
- Info: Theme Customization API
- クラス: WP_Customize_Manager() class /en,
- メソッド: WP_Customize_Manager->add_setting() /en,
- メソッド: WP_Customize_Manager->add_section() /en,
- メソッド: WP_Customize_Manager->add_control() /en,
- メソッド: WP_Customize_Manager->get_setting() /en,
- フック: customize_register /en,
- フック: customize_preview_init /en,
- フック: customize_controls_print_styles /en,
- フック: customize_controls_print_scripts /en,
- フック: customize_controls_init /en,
- フック: customize_controls_enqueue_scripts /en
このページ「テーマカスタマイズ API」は一部未翻訳です。和訳や日本語情報を加筆してくださる協力者を求めています。