아래 코드를 그대로 쓰면 된다.
단지, 파란색 부분을 수정해줘야 한다.
- 도메인 주소
- 카테고리 지정 : categories=5 (WordPress 관리자 대시보드에서 **”게시글” > “카테고리”**로 이동합니다. 카테고리 목록에서 각 카테고리의 ID를 확인할 수 있습니다. 마우스를 특정 카테고리 이름 위에 올려놓으면 브라우저 하단에 해당 카테고리의 ID가 표시된 링크를 볼 수 있다.
- 글의 목록 수 지정 : per_page=100
<div style=”margin-top: 20px”>
<input type=”text” id=”search-input” placeholder=”검색어 입력” />
<button id=”search-button” class=”custom-button”>검색</button>
<button id=”reset-button” class=”custom-button”>전체 보기</button>
</div><br>
<!– latest-posts 컨테이너 –>
<div id=”latest-posts-container”></div>
<script>
document.addEventListener(‘DOMContentLoaded’, function() {
fetchPosts();
});
document.getElementById(‘search-button’).addEventListener(‘click’, function() {
var searchQuery = document.getElementById(‘search-input’).value;
fetchPosts(searchQuery);
});
document.getElementById(‘reset-button’).addEventListener(‘click’, function() {
document.getElementById(‘search-input’).value = ”;
fetchPosts();
});
function fetchPosts(query = ”) {
var apiUrl = ‘https://yourdomain.com/wp-json/wp/v2/posts?categories=5&per_page=100‘;
if (query) {
apiUrl += `&search=${query}`;
}
fetch(apiUrl)
.then(response => response.json())
.then(posts => {
if (query) {
posts = posts.filter(post => post.title.rendered.includes(query));
}
displayPosts(posts);
})
.catch(error => console.error(‘Error fetching posts:’, error));
}
function displayPosts(posts) {
var postsContainer = document.getElementById(‘latest-posts-container’);
postsContainer.innerHTML = ”; // Clear previous results
if (posts.length === 0) {
postsContainer.innerHTML = ‘<div>검색 결과가 없습니다.</div>’;
return;
}
posts.forEach(post => {
var postElement = document.createElement(‘div’);
postElement.innerHTML = `<a href=”${post.link}”>${post.title.rendered}</a>`;
postsContainer.appendChild(postElement);
});
}
</script>