ショートコードを作成
まずは使用するショートコードを作成していきます。
ここでは例として<div class="example"></div>
を出力するというもので、functions.php
に下記を記述します。
functions.php
function example_shortcode( $atts, $content = null ) {
return '<div class="example">' . $content . '</div>';
}
add_shortcode( 'example', 'example_shortcode' );
上記ショートコードを登録すると、例えば[example]lorem ipsum[/example]
といった形でショートコードを使用するとフロントでは<div class="example">lorem ipsum</div>
のように出力されます。
ショートコードの作成についての詳細は以下で確認できます。
ビジュアルエディタにボタンを追加する
ビジュアルエディタにクリックすると上で作成したショートコードが挿入されるボタンを追加します。
まず、ボタン押下時の動きなどを指定するJSとしてeditor-button.js
(ファイル名は任意のもので可)を作成して下記のように記述します。
editor-button.js
(function() {
tinymce.create( 'tinymce.plugins.example_shortcode_button', {
init: function( ed, url ) {
ed.addButton( 'example', {
title: 'example shortcode',
icon: 'code',
cmd: 'example_cmd'
});
ed.addCommand( 'example_cmd', function() {
var selected_text = ed.selection.getContent(),
return_text = '[example]' + selected_text + '[/example]';
ed.execCommand( 'mceInsertContent', 0, return_text );
});
},
createControl : function( n, cm ) {
return null;
},
});
tinymce.PluginManager.add( 'example_shortcode_button_plugin', tinymce.plugins.example_shortcode_button );
})();
特に変更する必要があるのはreturn_text
の部分で、ここでボタンをクリックした際に呼び出したいショートコードを指定しておきます。
その他の部分は「example」となっている箇所を中心に任意のものに変更してください。
次に作成したJS(editor-button.js
)の読み込みとショートコードを呼び出すためのボタンをエディタに追加するために下記をfunctions.php
に記述します。
この場合はeditor-button.js
がfunctions.php
と同階層にある想定なので、別階層にある場合はパスを任意のものに変更してください。
functions.php
add_filter( 'mce_external_plugins', 'add_add_shortcode_button_plugin' );
function add_add_shortcode_button_plugin( $plugin_array ) {
$plugin_array[ 'example_shortcode_button_plugin' ] = get_template_directory_uri() . '/editor-button.js';
return $plugin_array;
}
add_filter( 'mce_buttons', 'add_shortcode_button' );
function add_shortcode_button( $buttons ) {
$buttons[] = 'example';
return $buttons;
}

実装後はこのイメージのようになり、ボタンをクリックするとエディタ内に[example][/example]
というショートコードが挿入されるのを確認できます。
TinyMCEにボタンを追加する方法についての詳細は以下で確認できます。
テキストエディタにボタンを追加する
次にテキストエディタに同じくクリックするとショートコードが挿入されるボタンを追加します。
実装にはクイックタグを利用するのでfunctions.php
に下記のように記述し、QTags.addButton()
の第3・第4パラメータに挿入したいショートコードを指定します。
functions.php
add_action( 'admin_print_footer_scripts', 'add_shortcode_quicktags' );
function add_shortcode_quicktags() {
if ( wp_script_is('quicktags') ) {
?>
<script>
QTags.addButton( 'example_shortcode', '[example]', '[example]', '[/example]' );
</script>
<?php
}
}

実装後はこのイメージのようになり、ビジュアルエディタのときと同様でボタンをクリックするとエディタ内に[example][/example]
というショートコードが挿入されるのを確認できます。
クイックタグについての詳細は以下で確認できます。