記事のコメントの投稿と表示をテンプレートに直接書いてみる
記事のコメント部分について、テンプレートに直接書いてみようと思います。
前提は下記のとおりです。
- WordPress 4.9.2 で実施
- 誰でもコメントできる(管理画面の「設定」→「ディスカッション」で、投稿のデフォルト設定と他のコメント設定のチェックボックスは、「新しい投稿へのコメントを許可する」のみチェックを入れて、それ以外のチェックは外しています。)
- 記事ページ内でのコメントの編集やコメントに対するリプライ機能はなし
single.php
- コメントフォーム
-
<form id="commentform" action="<?php echo home_url( '/wp-comments-post.php' ); ?>" method="post">
<textarea id="comment" name="comment"></textarea>
<input id="author" name="author" type="text" value="" />
<input name="submit" type="submit" id="submit" class="submit" value="コメントを送信" />
<input type="hidden" name="comment_post_ID" value="<?php the_id(); ?>" id="comment_post_ID" />
<input type="hidden" name="comment_parent" id="comment_parent" value="0" />
</form> - コメント表示
-
<?php
$comments = get_comments( 'post_id='.get_the_id().'&status=approve&type=comment&orderby=comment_date&order=ASC' );
function view_comment($comments) {
$t = '';
if (count($comments) > 0) {
foreach ( $comments as $comment ) {
$t .= $comment->comment_ID;
$t .= $comment->comment_content;
$t .= $comment->comment_date;
$t .= $comment->comment_author;
}
} else {
$t .= 'まだコメントはありません。';
}
return $t;
}
echo view_comment($comments);
?>
コメントエリアについて、これがミニマムな設定かと。これにタグやらCSSを整えてあげることでうまく仕上がるかと思います。
最低限のカスタマイズ
投稿者名のhtmlタグを無効化する
- 変更前
- $t .= $comment->comment_author;
- 変更後
- $t .= htmlspecialchars($comment->comment_author, ENT_QUOTES, 'UTF-8');
コメントテキスト内のhtmlタグを無効化し、コメントの改行コードをbrタグに変換する
- 変更前
- $t .= $comment->comment_content;
- 変更後
-
$comment_text = $comment->comment_content;
$comment_text = htmlspecialchars($comment_text, ENT_QUOTES, 'UTF-8');
$comment_text = preg_replace('/\r\n/', '<br />', $comment_text);
$comment_text = preg_replace('/\r/', '<br />', $comment_text);
$comment_text = preg_replace('/\n/', '<br />', $comment_text);
$t .= $comment_text;
日付の秒数は表示せず、年月日表示する
- 変更前
- $t .= $comment->comment_date;
- 変更後
- $t .= date("Y年n月j日 H:i", strtotime($comment->comment_date));