WordPress3から追加されたcomment_form()関数の引数を上手に使ってみる

ブログといえばコメント。

そのコメント入力欄はWordPress3.0.0からcomment_form()という関数を利用することができるようになっています。

そのcomment_form()関数の引数をばらしてちょっとだけ上手に使ってみます。

comment_form関数はWordPress3から実装されていてTwentyTenでも利用されていますが、実際どのくらいの引数があって、どういう使い方するの?ってのが結構あります。

comment_form()関数の使いどころ

comment_form()関数は基本的に「comments.php」の中に記述してあげます。

また、引数とフィルタを利用してあげることで柔軟にいろいろな事をできるようになります。

comment_form()関数を利用するメリット

この関数が用意されてから、新しくアクション・フィルタが追加され、コメントフォームの操作をより柔軟に操作できるようになっているためです。

コメント欄のプラグインや、自前のアクションフィルタ・フックを登録したりといろいろ便利です。

関数で利用できる引数

関数で利用できる引数(かっこの中に各やつ)は2つあります。

  • $args
  • $post_id

これらが指定できます。

初期値は

  • $args:array()「空っぽの配列」
  • $post_id:null「無指定」

となります。

$post_idは現在の投稿IDを指定しますが、これはWordPress側が勝手に解釈してくれるようになっているので、基本は指定しなくてもOKです。

$argsは後述にて。

$argsで指定できる物

$argsはかなりの数の指定をすることができるようになっていて、以下のようになっています。

// 以下抜粋
$defaults = array(
	'fields'               => apply_filters( 'comment_form_default_fields', $fields ),
	'comment_field'        => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>',
	'must_log_in'          => '<p class="must-log-in">' .  sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
	'logged_in_as'         => '<p class="logged-in-as">' . sprintf( __( 'Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>' ), admin_url( 'profile.php' ), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
	'comment_notes_before' => '<p class="comment-notes">' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '</p>',
	'comment_notes_after'  => '<p class="form-allowed-tags">' . sprintf( __( 'You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: %s' ), ' <code>' . allowed_tags() . '</code>' ) . '</p>',
	'id_form'              => 'commentform',
	'id_submit'            => 'submit',
	'title_reply'          => __( 'Leave a Reply' ),
	'title_reply_to'       => __( 'Leave a Reply to %s' ),
	'cancel_reply_link'    => __( 'Cancel reply' ),
	'label_submit'         => __( 'Post Comment' ),
);

いっぱいありますね。

いっぱいあるので、用途別にまとめてみます。

コメント入力欄

コメント入力欄は「投稿者名」「投稿者メールアドレス」「投稿者のWebサイトURL」「コメントフィールド」の4つがあります。

該当する言葉は、

  • fields
  • comment_field

の2つです。

fieldsの初期値は

$fields =  array(
	'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
	            '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',
	'email'  => '<p class="comment-form-email"><label for="email">' . __( 'Email' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
	            '<input id="email" name="email" type="text" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></p>',
	'url'    => '<p class="comment-form-url"><label for="url">' . __( 'Website' ) . '</label>' .
	            '<input id="url" name="url" type="text" value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></p>',
);

のようになっていて、既に綺麗に整形されています。

が、pじゃなくてdivを使いたいとか、必須の部分はemを使いたいなど、要望はあると思います。

その場合は以下のように指定してあげることで、整形することが可能です。

$args = array(
	'fields' => array(
		'author' => '<p class="comment-form-author"><label for="author">お名前</label> <span class="required">*</span>'.
	            '<input id="author" name="author" type="text" value="" size="30" /></p>',

	)
);

このように、各項目を指定していきます。

ですが、これだと「投稿者の初期値設定」や「必須項目の調整」の融通がききません。

ここのちょっとだけ上手な使い方は下部に用意したおまけに記載しています。

メッセージ系

メッセージ系ではログインしていない場合のメッセージや、「◯◯でログインしています」などのメッセージを変更することが出来ます。

  • must_log_in
  • logged_in_as
  • comment_notes_before
  • comment_notes_after

の4つの言葉で指定することが出来ます。

それぞれの初期値は、

  • must_log_in:コメントするにはログインが必須であることを促すメッセージ
  • logged_in_as:現在ログインしているユーザー名を示すメッセージ
  • comment_notes_before:コメントフォームの手前(メールアドレスは表示されません)に表示されるメッセージノート
  • comment_notes_after:コメントフォームの後(タグの許可リスト)を表示するメッセージノート

となっています。

メッセージ回りはWordPress側で綺麗に整形されて、日本語も表示されているので、手を加えることはめったに無いと思いますが、メッセージノートの前後を入れ替える場合は以下のようにします。

$args = array(
	'comment_notes_before' => '<p class="comment-notes">メールアドレスは表示されません。 <span class="required">*</san> は必須項目です。</p>',
	'comment_notes_after'  => '<p class="form-allowed-tags">利用可能なHTMLタグは次のとおりです:<code>%s</code>' ), allowed_tags() ) . '</p>',
);

ただ、これもまたまだ必須項目の調整に融通が聞いていません。

これも同様におまけとして、ページ下部にサンプルソースを掲載しています。

タグのid属性

タグのid属性も好きなものに変更できるようになっており、次のように指定するだけで好きなidを設定することが可能です。

$args = array(
	'id_form'              => 'my_comment_form',
	'id_submit'            => 'submit_button',
);

タイトル系

タイトル系では、日本語表示だと「コメントをどうぞ」の部分と、スレッドコメントを許可している場合の「◯◯へコメント」のような表記の部分になります。

これも指定は簡単で、以下のように記述するだけで設定することが可能です。

$args = array(
	'title_reply'          => 'コメントをどうぞどうぞ',
	'title_reply_to'       => '%s へのコメント',
);

リンク・ボタン系

リンク・ボタン系はそのままで、他ユーザーへの返信時に表示される(コメントをキャンセル)文字とフォームの送信ボタンの表示文字を変更することが出来ます。

設定するには以下のように指定します。

$args = array(
	'cancel_reply_link'    => 'コメントをキャンセルしてやるぜ',
	'label_submit'         => '仕方ないのでコメントを投稿してあげる',
);

以上で、comment_form()関数の引数の説明は終りです。

これだけあるとさすがにどれをどう指定していいのかも迷ってきます。

おまけ

ちょっとだけ便利に使うために、comment_form()関数をラップした関数を作ってみました。

if(!function_exists("convenience_comment_form")):
/**
 * ちょっとだけ使いやすいコメントフォームを提供する関数
 * 引数はもとのcomment_form関数とほぼ同じ。
 * --
 * 追加した引数
 * required
 *  必須項目のマークを指定する。 デフォルトで、「<span class="required">*</span>」となる。
 * required_notes
 *  「*マークは必須項目です」のような表示をするメッセージノート。
 *   初期値は「%1$sは必須項目です。」となる。
 *   %1$sには、上記 required の内容に置き換えられる。
 */
function convenience_comment_form($args = array(), $post_id = null) {
	wp_parse_args($args, array(
		"required" => '<span class="required">*</span>',
		"require_note" => '%1$sは必須項目です。'
	));

	// コメントユーザーのデフォルト値を取得
	$commenter = wp_get_current_commenter();
	$req = get_option( 'require_name_email' );
	$aria_req = ( $req ? " aria-required='true'" : '' );

	$required_notes = null;
	if($req) {
		$required_notes = sprintf(
			$args["required_notes"], $args["required"]
		);
	}

	foreach($args["fields"] as $field_name => $field) {
		$args["fields"][$field_name] = sprintf(
			$field,
			($req ? $args["required"] : ''), // 必須項目の設定
			esc_attr($commenter["comment_author". str_replace("author", "", $field_name)]), // 初期値
			$aria_req
		);
	}

	// comment_notes_before の設定
	if($args["comment_notes_before"]) {
		$args["comment_notes_before"] = sprintf(
			$args["comment_notes_before"], $required_notes
		);
	}

	comment_form($args, $post_id);
}
endif;

この内容をテーマのfunctions.phpに記述し、comments.phpからは以下のように呼び出します。

<?php convenience_comment_form(array(
	"required" => '<em class="required">*</em>',
	// %1$s は required で指定した内容に置き換わる
	"required_notes" => '%1$sは必須項目です。',
	"fields" => array(
		"author" => '<p class="comment-form-author"><label for="hogehoge">お名前</label>%1$s'.
					'<input id="hogehoge" type="text" name="author" value="%2$s"%3$s /></p>',
		"email"  => '<p class="comment-form-email"><label for="email">メールアドレス</label>%1$s'.
					'<input type="text" id="email" name="email" value="%2$s"%3$s /></p>',
		"url"    => '<p class="comment-form-url"><label for="url">Webサイト</label>%1$s'.
					'<input type="text" id="url" name="url" value="%2$s"%3$s /></p>',
	),
	// %1$s の部分は required_notes で指定した内容に置き換わる
	'comment_notes_before' => '<p class="comment-notes">メールアドレスは表示されません。%1$s</p>'
)); ?>

以上、comment_form()関数についてのまとめでしたdouble exclamation わーい (嬉しい顔)

コメントは受け付けていません。