사이트의 댓글이 많아지면 사용자들이 자신이 단 댓글을 찾기가 쉽지 않을 수 있습니다. 실제로 어디에 댓글을 달았는지 알 수가 없어 비슷한 댓글을 다시 다는 사용자들도 간혹 있습니다. 댓글을 검색할 수 있는 페이지를 만들면 사용자들이 자신이 단 댓글을 쉽게 찾을 수 있습니다.
다른 방법으로 답글이 달릴 때 댓글 작성자에게 이메일로 알림을 보내는 워드프레스 플러그인을 사용하는 것도 고려할 수 있습니다. 이런 기능을 하는 플러그인으로 Comment Reply Email Notification이 있습니다.
워드프레스 댓글만 검색하는 페이지 만들기 (댓글 검색 기능 추가)
이 워드프레스 블로그에는 현재 1만 개가 넘는 댓글이 달렸으며 현재도 꾸준히 댓글이 달리고 있습니다.
간혹 자신이 어디에 댓글을 달았는지 알 지 못하는 분들이 계십니다. 이를 위해 이 블로그에는 모든 댓글을 최신 댓글에서 오래된 댓글 순서로 표시하는 최신 댓글 페이지를 만들었습니다.
이번에 추가로 댓글을 검색할 수 있는 기능도 추가했습니다. 키워드로 검색하거나 댓글 작성자 이름으로 쉽게 댓글을 검색할 수 있어 이전보다 빠르고 쉽게 자신이 단 댓글을 찾을 수 있도록 했습니다.

실제 작동을 여기에서 확인할 수 있습니다.
댓글 검색 기능 추가하기
댓글 검색 기능을 숏코드로 추가하는 방법에 대하여 살펴보겠습니다.
먼저 다음 코드를 테마의 함수 파일에 추가하도록 합니다. 차일드 테마를 만들어 작업합니다.
// Enqueue jQuery and our custom script
function enqueue_comment_search_scripts() {
wp_enqueue_script('jquery');
// Add our custom script
wp_enqueue_script('comment-search', get_stylesheet_directory_uri() . '/js/comment-search.js', array('jquery'), '1.0.0', true);
// Add localized variables to the script including our nonce
wp_localize_script('comment-search', 'cs_vars', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('comment_search_nonce') // Add nonce for security
)
);
}
add_action('wp_enqueue_scripts', 'enqueue_comment_search_scripts');
// Handle AJAX request
function handle_comment_search() {
// Verify nonce
if( !isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'comment_search_nonce') ) {
die('Permission denied');
}
$keyword = sanitize_text_field($_POST['keyword']);
$args = array(
'search' => $keyword,
);
$comments = get_comments($args);
$results = array();
foreach($comments as $comment) {
$results[] = array(
'comment_ID' => $comment->comment_ID,
'comment_author' => esc_html($comment->comment_author),
'comment_content' => esc_html($comment->comment_content),
'comment_post_ID' => $comment->comment_post_ID,
'post_title' => esc_html(get_the_title($comment->comment_post_ID)),
'post_permalink' => get_permalink($comment->comment_post_ID) // Add this line
);
}
if(!empty($results)) {
$response = array(
'status' => 'success',
'data' => $results
);
} else {
$response = array(
'status' => 'fail'
);
}
echo json_encode($response);
die();
}
add_action('wp_ajax_comment_search', 'handle_comment_search'); // If user is logged in
add_action('wp_ajax_nopriv_comment_search', 'handle_comment_search'); // If user is not logged in
차일드 테마(자식 테마) 폴더에 js 폴더를 만들고 comment-search.js 파일을 만들고 다음과 같은 자바스크립트 코드를 추가합니다.
document.addEventListener("DOMContentLoaded", function() {
var form = document.getElementById("comment-search-form");
var input = document.getElementById("comment-search-input");
var resultsDiv = document.getElementById("comment-search-results");
form.addEventListener("submit", function(e) {
e.preventDefault();
// Show the resultsDiv when form is submitted
resultsDiv.classList.remove('hidden');
var keyword = input.value;
var xhr = new XMLHttpRequest();
xhr.open("POST", cs_vars.ajaxurl, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
if (response.status === "success") {
var html = "<ul>";
response.data.forEach(function(comment) {
html += "<li><strong>" + comment.comment_author + "</strong> on ";
html += '<a href="' + comment.post_permalink + '#comment-' + comment.comment_ID + '">' + comment.post_title + '</a>: ';
html += '<blockquote>' + comment.comment_content + '</blockquote></li>';
});
html += "</ul>";
resultsDiv.innerHTML = html;
} else {
resultsDiv.innerHTML = "<p>No results found.</p>";
}
}
};
var params = "action=comment_search&keyword=" + encodeURIComponent(keyword) + "&nonce=" + cs_vars.nonce;
xhr.send(params);
});
});
그리고 다음 CSS 코드를 추가합니다. (차일드 테마 폴더의 스타일시트 파일(style.css)에 추가할 수 있습니다.)
.hidden {
display: none;
}
이제 숏코드를 만듭니다. 테마 함수 파일에 다음과 같은 코드를 추가합니다.
function comment_search_form_shortcode() {
ob_start();
?>
<div class="comment-search-container">
<form id="comment-search-form" method="post" action="">
<input type="text" id="comment-search-input" name="keyword" placeholder="Search keyword...">
<input type="submit" value="Search">
</form>
<div id="comment-search-results" class="hidden"></div>
</div>
<?php
return ob_get_clean();
}
add_shortcode('comment_search_form', 'comment_search_form_shortcode');
이제 다음 숏코드를 콘텐츠에 추가하여 댓글 검색 폼을 표시할 수 있습니다.
[comment_search_form]
상기 코드를 사용하면 키워드나 댓글 작성자 이름으로 댓글을 검색할 수 있는 검색 상자가 표시됩니다. '더보기' 버튼이나 페이지네이션을 추가하는 것이 가능하지만, 실력 부족으로 구현하지 못했습니다.😥😥 대신, 제 블로그에서는 일치되는 결과가 40개까지만 표시되도록 제한했습니다.
댓글 검색 폼과 검색 결과 섹션의 스타일은 CSS로 조정할 수 있습니다.
제 블로그에서는 다음과 같은 CSS 스타일을 사용했습니다.
/* Comment Search Form Styles */
#comment-search-form {
max-width: 600px;
margin: 20px auto 60px auto;
padding: 25px;
border: 1px solid #d8d8d8;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
background-color: #ffffff;
}
#comment-search-input {
width: 70%;
padding: 12px 15px;
border: 1px solid #d8d8d8;
border-radius: 6px;
font-size: 16px;
transition: border-color 0.3s, box-shadow 0.3s;
}
#comment-search-input:focus {
border-color: #0099cc;
box-shadow: 0 1px 4px rgba(0, 153, 204, 0.2);
outline: none;
}
#comment-search-form input[type="submit"] {
padding: 12px 25px;
background-color: #0099cc;
color: #ffffff;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.3s, box-shadow 0.3s;
}
#comment-search-form input[type="submit"]:hover {
background-color: #007aa3;
box-shadow: 0 2px 6px rgba(0, 153, 204, 0.2);
}
/* Comment Search Results Styles */
#comment-search-results {
max-width: 800px;
margin: 20px auto 60px auto;
padding: 25px;
border: 1px solid #d8d8d8;
border-radius: 8px;
background-color: #ffffff;
}
#comment-search-results ul {
list-style-type: none;
padding: 0;
}
#comment-search-results li {
padding: 15px;
border-bottom: 1px solid #e8e8e8;
}
#comment-search-results li:last-child {
border-bottom: none;
}
#comment-search-results strong {
font-size: 18px;
color: #333;
}
#comment-search-results blockquote {
margin: 15px 0;
padding: 15px;
border-left: 4px solid #0099cc;
background-color: #e9f5f9;
font-style: italic;
color: #555;
}
#comment-search-results a {
color: #0099cc;
text-decoration: none;
transition: color 0.3s;
}
#comment-search-results a:hover {
color: #007aa3;
}
.hidden {
display: none;
}
@media (max-width: 768px) {
.comment-search-container { padding: 0px 15px; }
#comment-search-form {
line-height: 3.5em;
}
}
GeneratePress 테마를 사용하는 경우 제 블로그의 댓글 검색 페이지에 있는 댓글 검색 폼과 비슷하게 표시될 것입니다. 다른 테마를 사용하는 경우, 테마의 스타일에 따라 적절히 CSS 코드를 변경할 수 있습니다.
상기 코드에서 에러가 있거나 개선 사항이 있다면 아래 댓글을 통해 알려주시기 바랍니다.
댓글 남기기