WordPress:ヴィジュアルエディターにボタンを追加する方法
WordPressのヴィジュアルエディターに新しいボタンを追加する方法です。
今回は、ヴィジュアルエディターに下図のようなボタンを追加します。

テキストを選択してボタンをクリックすると、下記のようなタグが仕込まれる仕様です。
HTML
<a href="https://itti.jp/contct/" class="test">
{任意のテキスト}
<i><i>
</a>仕込まれるタグは変更できるので、好きなタグをボタン一つで挿入することができます。
プラグイン「Advanced Editor Tools (旧 TinyMCE Advanced)」をインストールしていても使えます。
ボタンの追加方法
早速ボタンを追加していきましょう。
必要なファイル
ボタンを追加するには下記のファイルが必要となります。
- ボタンアイコン用のpngファイル(サイズは20X20)
- tinymce_quotebutton.js
- swpbtn-shortcode.php
エディターに表示させるボタンアイコンは事前に作成しておきましょう。
JavaScript「tinymce_quotebutton.js」の用意
JavaScriptファイル「tinymce_quotebutton.js」を新しく作成して、下記を記載します。
マーキングしている箇所は適宜ご変更ください。
javascript
(function() { tinymce.PluginManager.add( 'swpquote', function( editor, url ) { editor.addButton('swpquote', { title: 'お問い合わせボタン', //ボタンのAltタイトル cmd: 'swpquote', image: url + '/contact.png', //エディターアイコン用のpng }); editor.addCommand('swpquote', function() { var selected_text = editor.selection.getContent({ 'format': 'html' }); if ( selected_text.length === 0 ) { alert( 'テキストを選択してください' ); //テキストを選択してない時のアラート return; } var open_column = '<a href="https://itti.jp/contact/" class="test">'; var close_column = '<i></i></a>'; var return_text = ''; return_text = open_column + selected_text + close_column; editor.execCommand('mceReplaceContent', false, return_text); return; }); });})();エディターに書かれたテキストを「open_column」と「close_column」のタグで挟む仕様ですね。
「swpbtn-shortcode.php」の用意
ヴィジュアルエディターをカスタマイズするためのPHPファイルを用意します。
下記のコードをコピペします。
PHP
<?phpadd_action( 'after_setup_theme', 'swp1_theme_setup' );if ( ! function_exists( 'swp1_theme_setup' ) ) {function swp1_theme_setup(){add_action( 'init', 'swp1_buttons' );}}if ( ! function_exists( 'swp1_buttons' ) ) {function swp1_buttons() {if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {return;}if ( get_user_option( 'rich_editing' ) !== 'true' ) {return;}add_filter( 'mce_external_plugins', 'swp1_add_buttons' );add_filter( 'mce_buttons', 'swp1_register_buttons' );}}if ( ! function_exists( 'swp1_add_buttons' ) ) {function swp1_add_buttons( $plugin_array ) {$plugin_array['swpquote'] = get_stylesheet_directory_uri().'/assets/js/tinymce_quotebutton.js';return $plugin_array;}}if ( ! function_exists( 'swp1_register_buttons' ) ) {function swp1_register_buttons( $buttons ) {array_push( $buttons, 'swpquote' );return $buttons;}}functions.phpの編集
functions.phpに下記を追記します。
functions.php
include "swpbtn-shortcode.php";以上でファイルの編集は完了です。
ファイルのアップロード
テンプレートのディレクトリに「swpbtn-shortcode.php」と、編集した「functions.php」をアップします。
「tinymce_quotebutton.js」と「アイコン用のpngファイル」はテンプレートのディレクトリーの「/assets/js/」にアップします。
アップロードは以上です。
ヴィジュアルエディターを確認するとボタンが追加されています。

テキストを選択してボタンをクリックして、設定したタグで囲まれていればOKです。


