ビジュアルエディタに独自ボタンを追加する
投稿画面のビジュアルエディタに独自ボタンを追加したい場合、下記のように設定します。
(例: h2ボタン、h3ボタンを追加)
1. テーマのfunctions.phpに下記のように記載します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * 独自ボタンを追加します。 */ function custom_mce_buttons( $buttons ) { $buttons[] = 'button_h2'; // <h2>用 $buttons[] = 'button_h3'; // <h3>用 return $buttons; } /** * 独自ボタン用のスクリプトの読み込みを追加します。 */ function custom_mce_external_plugins( $plugin_array ) { $plugin_array['custom_button_script'] = get_template_directory_uri() . "/tinymce.js"; return $plugin_array; } add_filter( 'mce_buttons', 'custom_mce_buttons' ); add_filter( 'mce_external_plugins', 'custom_mce_external_plugins' ); |
2. テーマフォルダに「tinymce.js」というファイルを作成(1.で指定したファイル名)し、下記のような内容を記載します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
(function() { tinymce.create('tinymce.plugins.MyButtons', { init : function(ed, url) { // h2ボタン設定 ed.addButton( 'button_h2', { title : 'h2', image : url + '/h2.png', cmd: 'button_h2_cmd' }); // h2ボタンの動作 ed.addCommand( 'button_h2_cmd', function() { var selected_text = ed.selection.getContent(); var return_text = ''; return_text = '<h2>' + selected_text + '</h2>'; ed.execCommand('mceInsertContent', 0, return_text); }); // h3ボタン設定 ed.addButton( 'button_h3', { title : 'h3', image : url + '/h3.png', cmd: 'button_h3_cmd' }); // h3ボタンの動作 ed.addCommand( 'button_h3_cmd', function() { var selected_text = ed.selection.getContent(); var return_text = ''; return_text = '<h3>' + selected_text + '</h3>'; ed.execCommand('mceInsertContent', 0, return_text); }); }, createControl : function(n, cm) { return null; }, }); /* Start the buttons */ tinymce.PluginManager.add( 'custom_button_script', tinymce.plugins.MyButtons ); })(); |
3. tinymce.jsと同じ位置にボタンのアイコンを設置します(例ではh2.png、h3.png)。
※ 2.にある「image : url + '/h3.png'」のような箇所を変更すればアイコンの設置場所を変更できます。
結果:
※ アイコンの画像を作成・設置していない場合は枠だけ表示されます。