はじめに
以前の記事では、WordPressのコメント本文を短縮して表示する方法を紹介しました。
今回は、コメント欄に表示する内容を最上位のコメントのみにし、返信や再返信を折りたたみ表示します。
最上位コメントに返信がある場合は「返信を表示」ボタンを追加し、クリックすると返信と再返信をまとめて表示します
この記事では、この方法について説明します。
完成イメージ

実装手順
以下の手順で実装します。
- ラベルJavaScriptを追加
以下のコードをjavascript.jsに追加します。
jQuery(function ($) { $('#comment-area li.depth-1').each(function () { const $children = $(this).children('ul.children').hide(); if (!$children.length) return; // ボタン追加 $(this).children('.comment-body').append( '<button type="button" class="comment-descendants-toggle">[返信を表示]</button>' ); }); // クリック処理 $('#comment-area').on('click', '.comment-descendants-toggle', function () { const $children = $(this).closest('li.depth-1').children('ul.children').toggle(); $(this).text($children.is(':visible') ? '[返信を閉じる]' : '[返信を表示]'); }); }); - ラベルCSSを追加
以下のコードをstyle.cssに追加します。
.comment-descendants-toggle { background: none; border: none; color: #0073aa; cursor: pointer; font-size: inherit; margin-top: 8px; padding: 0; text-decoration: underline; }
さいごに
今回紹介した方法を使えば、最上位コメントだけを最初に表示し、返信や再返信を必要に応じて開閉できるようになります。
コメントが多い場合でも、最初からすべての返信を表示せずに済むため、コメント欄をすっきりと整理できます。
返信を確認したいときだけボタンをクリックすればよいので、コメント一覧の見通しをよくしたい場合に活用できるカスタマイズです。