sori.studio

워드프레스 게시글에 댓글 기능 붙이기 (REST API 기반)

📘 워드프레스 REST API를 이용해서 나만의 사이트 만들기 - 6편

게시물에 댓글 보기 & 작성 기능 추가하기 (댓글 API 활용)

 

 

 

 

🧭 게시물 클릭 → 상세 페이지로 이동하는 구조

 

포스팅은 따로 하지 않았지만 게시물 목록 화면(index.html)에서 각 게시물 하단에 각 게시물의 링크를 클립보드에 복사할 수 있는 버튼과, 현재 게시물에 작성된 댓글의 개수를 보여지도록 구현해놓은 상태입니다.

메인화면에서 보여지는 모습


여기서 댓글을 클릭하면 id를 포함한 쿼리 파라미터를 이용해 상세 페이지로 이동하도록 설정했습니다.

location.href = `post.html?id=${post.id}`;

 

그렇게 이동한 post.html에서는 URL에서 id 값을 추출하여 해당 게시물을 불러옵니다.

const postId = new URLSearchParams(location.search).get("id");
const postUrl = `https://myDomain.com/wp-json/wp/v2/posts/${postId}`;

 

 

 

상세 페이지(post.html) 구조:

<h3>댓글</h3>
<div id="commentList"></div>

<h4>댓글 작성</h4>
<textarea id="commentContent" placeholder="댓글을 입력하세요"></textarea>
<button onclick="submitComment()">댓글 작성</button>

 

📥 댓글 불러오기 (GET):

워드프레스의 댓글 REST API는 아래처럼 간단히 호출할 수 있습니다.

const commentsUrl = `https://myDomain.com/wp-json/wp/v2/comments?post=${postId}`;
const res = await fetch(commentsUrl);
const comments = await res.json();

 

그리고 우리는 이것을 이용해 댓글 트리를 그려줍니다.

function renderComments(comments, parentId = 0, depth = 0) {
  return comments
    .filter(c => c.parent === parentId)
    .map(c => {
      const replies = renderComments(comments, c.id, depth + 1);
      const indent = `margin-left: ${depth * 20}px`;
      return `
        <div class="comment" style="${indent}">
          <div class="comment-author">${c.author_name}</div>
          <div class="comment-content">${c.content.rendered}</div>
          <button onclick="showReplyForm(${c.id}, ${depth + 1})">답글</button>
          <div id="reply-form-${c.id}"></div>
          ${replies}
        </div>
      `;
    }).join("");
}

 

📝 댓글 작성 (POST)

async function submitComment(parentId = 0) {
  const textareaId = parentId ? `replyContent-${parentId}` : "commentContent";
  const content = document.getElementById(textareaId).value.trim();
  if (!content) return alert("댓글을 입력해주세요.");

  const res = await fetch("https://myDomain.com/wp-json/wp/v2/comments", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`, // 로그인 토큰
    },
    body: JSON.stringify({
      post: postId,
      content,
      parent: parentId,
    }),
  });

  if (res.ok) {
    document.getElementById(textareaId).value = "";
    loadComments(); // 새로고침 없이 댓글 반영
  } else {
    const err = await res.json();
    alert("댓글 작성에 실패했습니다: " + (err.message || "오류"));
  }
}

 

 

 

답글에 댓글을 달기위한 답글 폼 동적 생성:

function showReplyForm(parentId, depth) {
  const container = document.getElementById(`reply-form-${parentId}`);
  container.innerHTML = `
    <textarea id="replyContent-${parentId}" placeholder="답글을 입력하세요"></textarea>
    <button onclick="submitComment(${parentId})">답글 작성</button>
  `;
}

 

완성된 모습

 

 

🎉 마무리하며

지금까지 총 6편에 걸쳐 워드프레스 REST API를 활용해 나만의 사이트를 만드는 과정을 정리해보았습니다.

사용자 인증부터 게시물 작성, 이미지 업로드, 검색, 댓글 기능까지, 기본적인 기능은 어느 정도 구현되었기에 이 연재는 여기서 마무리하려 합니다.


하지만 사실, 지금부터가 진짜 시작입니다.

이제부터는 각자의 스타일에 맞게 사이트를 만들어나가기 나름입니다.


예를 들면 이런 것들입니다:

  • ✏️ 게시물 수정/삭제 기능
  • 💬 댓글 수정/삭제 기능
  • 🎨 외형 꾸미기 (CSS 커스터마이징, 다크모드 등)

사실 1~2편 쓰는 동안 실제 구현은 대부분 끝나버렸고, 그 이후로는 글을 작성하기위해서 핵심기능만 빼내서 코드를 작성하자니 오히려 코드가 꼬이거나 귀찮아서 글을 쓰는 게 조금 버겁기도 했습니다.

 

그래도 누군가에게 이 시리즈가 도움이 되었기를 바라며, 이렇게 마무리합니다.

읽어주셔서 감사합니다! 🙇