Wonderful! WordPress

htmlエディタのクイックタグの追加

前のページ、「[caption]ショートコードとpタグの問題」において、途中、いきづまってcaptionの使用をやめてショートコードにて代用しようと思った時に、それならばショートコード自体の入力をなんとか楽にすることはできないものかと、ふと思いついたのがこのhtmlエディタのクイックタグ。
ここに新規にボタンを登録できないものだろうかとネットを探して見ると、やはりちゃんとそういうことが出来るようになっているのですね。

直接、/wp-includes/js/quicktags.jsを編集する方法とfunction.phpに関数を作る方法があります。
ちなみにこれができるプラグインもちゃんとあります。
wordpressのバージョンアップの事を考えるとシステムファイルを直接いじるよりも、関数を使った方が後々の事を考えると手間がかからずよいですね。

と、いうことなんですが、随分あとになって再びクイックタグを追加しようということになって、あれまぁ!と気がついたので、このあとその後日追記。

« 2020/5/22 追記: & 2022/05/25 加筆 : »
長らくお世話になっていたCrayon Syntax Highlighter といよいよお別れしようということになって。しかし、新しく使うことになったものは投稿への入力などは全く面倒見てくれず、そのときにエンティティなど施さなきゃならないことや、付加すべき指定されたタグのパターンなんてのもまず間違いなく忘れてしまいそうだし。と、いうことでこれもクイックタグに登録してしまえば便利で楽ちん、ということなったわけです。
で、改めてどうやるのかとwp-includes/js/quicktags.jsを見直していると、なんだかちょっと書式が違っていたりする。で、説明書きを読んでいたりすると、今ではやり方が違っているようで。クイックタグを登録するための関数があって、もっと簡単にできるようになっていると・・・。
と、今一度、この投稿を見直していると、嘘のような事実に気がついてしまったわけで・・・。クイックタグを簡単に登録できる関数は、あとになってできたものではなくて、この記事を書いていた当時からちゃんとあったものだと。その説明書きをちゃんとこの記事に載せていたではないか、と。そのJavascript の関数をアクションフックをつかって、php からjavascript を直にフッターにエコーさせろ!と書いてある。なんてこった!

まぁ、その当時はまだその意味がよくわからなかったのですね~、ざんねんですうっ~!
その説明書きは、このちょっと下の方にある古いもの「function for adding a button to Quicktags」とほんの少し違っている部分もありますが、ほぼ書いてあることは同じなのでそちらを。

と、いうことで →codex を参考にしてと。

そして WordPress が 6.0 になったら、QTags が定義されていない、というエラーが出るようになった。これは単純なことでスクリプトの読み込まれる順番が変わってしまったことによるもの。であるから、下のスクリプトに オンロードイベントを追加してあります。

<?php
	function appthemes_add_quicktags() {
		if ( wp_script_is( 'quicktags' ) ) {
?>
			<script type="text/javascript">
				window.addEventListener( 'load', () => {
			// QTags.addButton( 'そのボタン固有のID', 'ボタンに表示する文字列', '開始タグ', '必要ならその停止タグ', 'ショートカットキー用の文字' );
					QTags.addButton( 'paragraph', 'p', '<p>', '</p>', '' );
					QTags.addButton( 'hr', 'hr', '<hr>\n', '', 'h' );
					QTags.addButton( 'bold', 'bold', '<span style=\"font-weight:bold;\">', '</span>', 'w' );
					QTags.addButton( 'through', 'l-through', '<span style=\"text-decoration:line-through;\">', '</span>', 'e' );
					QTags.addButton( 'blue', 'blue', '<span class=\"bluecolor\">', '</span>', 'n' );
					QTags.addButton( 'red', 'red', '<span class=\"redcolor\">','</span>', 'r' );
					QTags.addButton( 'green', 'green', '<span class=\"greencolor\">', '</span>', 'g' );
					QTags.addButton( 'cop', 'cop', '<span class=\"copcolor\">', '</span>', 'y' );

			// QTags.addButton( 'そのボタン固有のID', 'ボタンに表示する文字列', コールバック関数 );
					QTags.addButton( 'strix_hl', 'highlighter', highlighter_popup );

					function highlighter_popup() {
						var doc = document;
	
						if ( null == doc.getElementById( 'highlighter' ) ) {
							var parr = doc.createElement('div');
						
							parr.id = 'highlighter';
							parr.style.cssText = 'position:fixed;width:700px;height:700px;top:calc(50vh - 350px);right:calc(50vw - 350px);padding:10px;background:purple;';
	
							doc.getElementById( 'wp-content-editor-container' ).appendChild( parr );
						}
					}
				});
			</script>
<?php
		}
	}
	add_action( 'admin_print_footer_scripts', 'appthemes_add_quicktags' );
?>

PHP
CopyExpand

17行目はボタンに関数を登録する場合のもの。コールバック関数の登録において、うっかり間違えそうなのは関数名にはクォートは必要ないこと。そしてその下はそのコールバック関数自体。
これだけでいいんですね。別にファイルを作ってアップロードする必要など無かったわけでした。実に簡単、簡潔です。ただこれだけのためにプラグインを使うというのもなんだかもったいないような気もしないでもない。何においても、functions.php のバックアップだけは怠り無く!

と、いうことなのでこの下の部分は必要ありません。(あっ!ちょっと下にある説明書きのところは必要かも?)
ただ、自分が自虐的に残しているためのものにすぎません。
とは言っても、2020/5/21 の時点においてもちゃんと機能はしていたのですけれど。あしからず。 ・・・

が、とりあえず理解しやすいファイルを直接編集する方法から。
対象のファイルは/wp-includes/js/ディレクトリにあるquicktags.jsファイルです。
このディレクトリには似た名前のファイルでquicktags.dev.jsというファイルがあります。
前述の.devの無いファイルは改行、タブ、スペースなど不必要なものが削除され、ファイルサイズを小さくしてあり、ファイルの内容を編集しようとする者にとってはとても見づらい状態になっています。
一方、.devの付いている方は、改行もインデントもスペースもあり編集しやすい状態にあります。
いくつかのページで.devのファイルを編集したのち、.devをとってリネームし、アップロードすればよいとの記述がありました。
.devは開発者の意味のdeveloper用ということだと思いますがいかがでしょうか。
ただ、ちょっと細かい内容が異なる部分があるので、私は.devの無い方(これが実相)のファイルを、必要な部分だけ読みやすいように改行を付けた後、編集しアップしました。

いざ、quicktags.jsの中身を見て見ます。
編集する部分はファイルの一番最後にあります。

edButtons[10]=new c.TagButton("strong","b","<strong>","</strong>","b");
edButtons[20]=new c.TagButton("em","i","<em>","</em>","i"),
edButtons[30]=new c.LinkButton(),
edButtons[40]=new c.TagButton("block","b-quote","\n\n<blockquote>","</blockquote>\n\n","q"),
edButtons[50]=new c.TagButton("del","del",'<del datetime="'+a+'">',"</del>","d"),
edButtons[60]=new c.TagButton("ins","ins",'<ins datetime="'+a+'">',"</ins>","s"),
edButtons[70]=new c.ImgButton(),
edButtons[80]=new c.TagButton("ul","ul","<ul>\n","</ul>\n\n","u"),
edButtons[90]=new c.TagButton("ol","ol","<ol>\n","</ol>\n\n","o"),
edButtons[100]=new c.TagButton("li","li","\t<li>","</li>\n","l"),
edButtons[110]=new c.TagButton("code","code","<code>","</code>","c"),
edButtons[120]=new c.TagButton("more","more","<!--more-->","","t"),
edButtons[130]=new c.SpellButton(),
edButtons[140]=new c.CloseButton()
})();
JavaScript
CopyExpand

そのままデフォルトでついているボタンが並んでいるのでわかりやすいです。
書式はというと、読みやすい.devファイルで探して見ると68~70行目に、

function edButton(id, display, tagStart, tagEnd, access, open) {
	return QTags.addButton( id, display, tagStart, tagEnd, access, '', -1 );
}
JavaScript
CopyExpand

とあり、そのまま見て行くと、280~303行目あたりに説明書きがあります。

/**
 * Main API function for adding a button to Quicktags
 *
 * Adds qt.Button or qt.TagButton depending on the args. The first three args are always required.
 * To be able to add button(s) to Quicktags, your script should be enqueued as dependent
 * on "quicktags" and outputted in the footer. If you are echoing JS directly from PHP,
 * use add_action( 'admin_print_footer_scripts', 'output_my_js', 100 ) or add_action( 'wp_footer', 'output_my_js', 100 )
 *
 * Minimum required to add a button that calls an external function:
 *     QTags.addButton( 'my_id', 'my button', my_callback );
 *     function my_callback() { alert('yeah!'); }
 *
 * Minimum required to add a button that inserts a tag:
 *     QTags.addButton( 'my_id', 'my button', '<span>', '</span>' );
 *     QTags.addButton( 'my_id2', 'my button', '<br />' );
 *
 * @param id string required Button HTML ID
 * @param display string required Button's value="..."
 * @param arg1 string || function required Either a starting tag to be inserted like "<span>" or a callback that is executed when the button is clicked.
 * @param arg2 string optional Ending tag like "</span>"
 * @param access_key string optional Access key for the button.
 * @param title string optional Button's title="..."
 * @param priority int optional Number representing the desired position of the button in the toolbar. 1 - 9 = first, 11 - 19 = second, 21 - 29 = third, etc.
 * @param instance string optional Limit the button to a specifric instance of Quicktags, add to all instances if not present.
 * @return mixed null or the button object that is needed for back-compat.
 */
qt.addButton = function( id, display, arg1, arg2, access_key, title, priority, instance ){
JavaScript
CopyExpand

これにより引数の意味するところがおおよそわかります。
いまひとつ不明なのがaccess引数ですが、ネットでは指定しなくてもいいと書いてあるページもありました。
調べてみるとこれはいわゆるアクセスキーです、ってそれじゃそのままか。たしかショートカットキーとかいうのでは。
良く見ると一番下の行、関数の引数部分がちゃんとaccess_keyとなってますね。
私の使っているFirefoxですと、altshift+アクセスキーでキーボードでボタンをフォーカス状態にできます。
フォーカス→エンターキーで入力ですね。
アクセスキーに関して詳しくはこちらをどうぞ»Access key from Wikipedia
最低限必要な引数はiddisplaytagStartの3つと書いてあるのでaccess_keyも省略可能です。
で、参考までに私が追加したのが以下のコードです。

edButtons[10]=new c.TagButton("strong","b","<strong>","</strong>","b");
edButtons[20]=new c.TagButton("em","i","<em>","</em>","i"),
edButtons[30]=new c.LinkButton(),
edButtons[40]=new c.TagButton("block","b-quote","\n\n<blockquote>","</blockquote>\n\n","q"),
edButtons[50]=new c.TagButton("del","del",'<del datetime="'+a+'">',"</del>","d"),
edButtons[60]=new c.TagButton("ins","ins",'<ins datetime="'+a+'">',"</ins>","s"),
edButtons[70]=new c.ImgButton(),
edButtons[80]=new c.TagButton("ul","ul","<ul>\n","</ul>\n\n","u"),
edButtons[90]=new c.TagButton("ol","ol","<ol>\n","</ol>\n\n","o"),
edButtons[100]=new c.TagButton("li","li","\t<li>","</li>\n","l"),
edButtons[110]=new c.TagButton("code","code","<code>","</code>","c"),
edButtons[120]=new c.TagButton("more","more","<!--more-->","","t"),
edButtons[130]=new c.SpellButton(),
edButtons[140]=new c.CloseButton(),
edButtons[150]=new c.TagButton('hr','hr','<hr />\n\n','','h'),
edButtons[160]=new c.TagButton('bold','bold','<span style=\"font-weight:bold;\">','</span>','w'),
edButtons[170]=new c.TagButton('blue','blue','<span class=\"bluecolor\">','</span>','n'),
edButtons[180]=new c.TagButton('red','red','<span class=\"redcolor\">','</span>','r'),
edButtons[190]=new c.TagButton('green','green','<span class=\"greencolor\">','</span>','g'),
edButtons[200]=new c.TagButton('yellow','yellow','<span class=\"yellowcolor\">','</span>','y'),
edButtons[210]=new c.TagButton('escape','escape','[es c=3]','[/es]','e')
})();
JavaScript
CopyExpand

ちなみに、一番最後のescapeは、「SyntaxHighlighterがつかえない!」で作った、簡単な文字列を手軽にエスケープするためのショートコードを入力するためのものです。"["、"]"のエスケープが出来なかったのでここだけ表示用に全角にしてありますが、実際は半角です。

これらのボタンの書式を編集したい場合は、/wp-includes/css/ディレクトリにあるeditor.cssファイルです。
このファイルにも同じように.dev付のファイルが存在します。
こちらのファイルは内容も同じ様なので、読みやすい.dev付を編集してリネームした後、アップしてもよいかと思います。
quicktags-toolbarでファイル内を検索すれば、関連する部分がすぐに見つかります。
一例として、私が手を入れた部分のcssです。

.quicktags-toolbar input{
	margin:2px 1px 4px;
	line-height:18px;
	display:inline-block;
	min-width:26px;
	padding:2px 4px;
	font:12px/18px Arial,Helvetica,sans-serif normal;
	color:#db7093;
	border:1px solid #c3c3c3;
	-webkit-border-radius:3px;
	border-radius:3px;
	background-color:#eee;
	background-image:-ms-linear-gradient(bottom,#e3e3e3,#fff);
	background-image:-moz-linear-gradient(bottom,#e3e3e3,#fff);
	background-image:-o-linear-gradient(bottom,#e3e3e3,#fff);
	background-image:-webkit-linear-gradient(bottom,#e3e3e3,#fff);
	background-image:linear-gradient(bottom,#e3e3e3,#fff)
}
.quicktags-toolbar input:hover{border-color:#aaa;background:#ddd}
.quicktags-toolbar input[value="link"]{text-decoration:underline}
.quicktags-toolbar input[value="del"]{text-decoration:line-through}
.quicktags-toolbar input[value="i"]{font-style:italic}
.quicktags-toolbar input[value="b"]{font-weight:bold}
.quicktags-toolbar input[value="blue"]{color:#0000ff}
.quicktags-toolbar input[value="red"]{color:#ff0000}
.quicktags-toolbar input[value="green"]{color:#008000}
.quicktags-toolbar input[value="yellow"]{color:#ffff00}
.quicktags-toolbar input[value="escape"]{color:#940023;font-style:italic}

CSS
CopyExpand

各要素は引数idではなくdisplayの値で指定していますね。なんか不思議?
以上で、動作しています。
くれぐれも元ファイルのバックアップをお忘れなく。
あと、データを追加するときに最後のカンマの有無にご注意を。
・・・

そして、function.phpに関数を作る方法です。
こちらも、とりあえずネットから取ってきたほとんどそのままの内容ですが。
流れとしては、追加するボタンをjsファイルで指定し、それを関数で読み込ませて登録するという感じです。

それではjsファイルの内容から。
add_quicktags.js

edButtons[edButtons.length]=new edButton('paragraph','p','<p>','</p>','');
edButtons[edButtons.length]=new edButton('hr','hr','<hr />\n\n','','h');
edButtons[edButtons.length]=new edButton('bold','bold','<span style=\"font-weight:bold;\">','</span>','w');
edButtons[edButtons.length]=new edButton('blue','blue','<span class=\"bluecolor\">','</span>','n');
edButtons[edButtons.length]=new edButton('red','red','<span class=\"redcolor\">','</span>','r');
edButtons[edButtons.length]=new edButton('green','green','<span class=\"greencolor\">','</span>','g');
edButtons[edButtons.length]=new edButton('yellow','yellow','<span class=\"yellowcolor\">','</span>','y');
edButtons[edButtons.length]=new edButton('escape','escape','[es c=3]','[/es]','e');
edButtons[edButtons.length]=new edButton('imgcaptl','imgcapt-l','<span class=\"imagescapt\">','</span>','m');
edButtons[edButtons.length]=new edButton('imgcapts','imgcapt-s','<span class=\"simagescapt\">','</span>','p');
edButtons[edButtons.length]=new edButton('br','br','<br />','','');
JavaScript
CopyExpand

そしてfunction.php内に記述する関数は、

function my_add_quicktags(){
	wp_enqueue_script(
		'my_add_quicktags',
		get_template_directory_uri().'/add-quicktags.js',
		array('quicktags')
	);
}
add_action('admin_print_scripts','my_add_quicktags');
PHP
CopyExpand

アクションフックを使って登録するわけです。
この場合のjsファイルはテーマと同じディレクトリにアップしてあります。
まぁ、こちらの方が実際の手間も少なくて済むかもしれません。
書式を変更する場合のcssファイルは同じです。
quicktags

これはとても便利です。
いままで手打ちしていたpタグや、ショートコードで入力していた部分もボタンを押せば一発です。ただ知らなかったというだけで随分面倒なことをしていました。
これでますますwordpressが好きになりましたね。

Leave a Reply!

JavaScript is necessary to send a comment.
You can edit and delete your comment if you input a edit key.
Edit key is necessary for attesting you when you edit and delete it.
The tag of HTML cannot be used in comment.
When you comment for the first time, it is displayed after the approval of the administrator.
Because I cannot speak English so much, it takes time to answer.
Required fields are marked *.

※Please enter more than 5 characters only alphabets.
※Edit or delete are possible for 2000 days after approval.

*

♠Simplistic Comment User Editable v4.0

♠When visitors leave comments on the site this site collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection.
♠This site does not use cookie when visitors leave comments and commenter edit comment.
♠This site uses Akismet to reduce spam. Learn how your comment data is processed.

Comments feed

Trackback URL : https://strix.main.jp/wp-trackback.php?p=25077

Sanbanse Funabashi
2011.01.01 sunrise

Top

スクロールさせるか画像をクリックすると元に戻ります。