近年、WordPressのバージョンが上がってからは、テーマの質や管理画面の編集機能が向上したことで、ソースファイルを直接編集する機会が減ってきました。
特に「外観 > カスタマイズ」では、画面を見ながらリアルタイムで編集した内容が反映されるのでとても便利です。
しかし、編集できるのはテーマによって限られた設定項目しかなく、特に「追加 CSS」はあるのに「追加 JavaScript」が無いってのはちょっと不便。
ってことで、なければ設定項目を追加しちゃいましょう!
設定項目を追加する
JavaScriptを追加したいなら以前の紹介したように直接記事に挿入する方法もありますが、今回はサイト全体に反映させたいので別の方法で行います。
それでは、WordPressのベーステーマとして作った「Under Material」の管理画面を改造することにします。
まずは、functions.phpを開いて以下を追加します。
function under_strap_theme_customize_register( $wp_customize ) {
    // Section
    $wp_customize->add_section( 'under_strap_theme_origin_scheme', array(
      'title'     => 'Add JavaScript',
      'priority'  => 200,
    ));
    // Textarea setting
    $wp_customize->add_setting( 'under_strap_theme_options', array(
      'default'   => '',
      'type'      => 'option',
      'transport' => 'postMessage',
    ));
    // Textarea control
    $wp_customize->add_control( 'under_strap_theme_options_origin_textarea', array(
      'settings'  => 'under_strap_theme_options',
      'label'     => 'Input JavaScript',
      'section'   => 'under_strap_theme_origin_scheme',
      'type'      => 'textarea',
    ));
}
add_action( 'customize_register', 'under_strap_theme_customize_register' );
説明
設定項目を追加する関数を用意します。
under_strap_theme_customize_register
その中で、以下の3つの設定を行います。
- add_section
 - 
title:追加する項目
priority:表示順 - add_setting
 - 
default:デフォルト値
type:’option’と入力しておく
transport:’postMessage’で保存後に公開。 - add_control
 - 
section:sectionのキー
settings:settingのキー
label:ラベル名
type:入力タイプ 
テーマに反映させる
あとは、追加した設定項目に入力した内容を表示したいテーマのパーツで呼び出すだけです。
今回の場合はfooter.phpに追加しました。
<?php if(get_option('under_strap_theme_options')): ?><script><?php echo get_option('under_strap_theme_options'); ?></script><? endif; ?>
完成したらこのようになります。
‘Add JavaScript’を追加
参考サイト
こちらのサイトにその他オプションなど、もっと詳しい内容が書いてあります。 WordPressのテーマカスタマイザーにオリジナルの項目を追加する方法 | UNORTHODOX WORKBOOK | Blog想像は付くと思いますが、今回はテキストエリアでしたがもちろん他の入力フォームも追加できますよ。
- textarea(テキストエリア)
 - checkbox(チェックボックス)
 - select(セレクトボックス)
 - radio(ラジオボタン)
 
これで管理がもっと楽になります。
あ、テーマをアップデートしたら消えてしまうので、子テーマを作った方が良いかと思います。
- Original:https://minory.org/theme-customizer-api.html
 - Source:Minory
 - Author:管理者
 
