`; } function renderGrid(posts) { const gridPosts = posts.slice(1); if (gridPosts.length === 0) { gridContainer.innerHTML = `
`; }).join(""); } function updatePagination() { pageInfo.textContent = "หน้า " + currentPage + " / " + totalPages; prevBtn.disabled = currentPage <= 1; nextbtn.disabled=currentPage>= totalPages; pagination.style.display = totalPages > 1 ? "flex" : "none"; } function renderPosts(posts) { renderFeatured(posts[0]); renderGrid(posts); updatePagination(); } function loadPosts() { featuredContainer.innerHTML = ""; gridContainer.innerHTML = ""; fetch(buildApiUrl()) .then(response => { totalPages = parseInt(response.headers.get("X-WP-TotalPages")) || 1; if (!response.ok) { throw new Error("ไม่สามารถโหลดบทความได้"); } return response.json(); }) .then(posts => { if (!posts || posts.length === 0) { featuredContainer.innerHTML = ""; gridContainer.innerHTML = `
ไม่พบบทความเพิ่มเติม
`; return; } gridContainer.innerHTML = gridPosts.map(post => { const image = getPostImage(post); const title = stripHtml(post.title.rendered); const excerptRaw = stripHtml(post.excerpt.rendered); const excerpt = excerptRaw.length > 115 ? excerptRaw.substring(0, 115) + "..." : excerptRaw; const category = getPostCategory(post); const link = post.link; return `ไม่พบบทความ
`; updatePagination(); return; } renderPosts(posts); }) .catch(error => { gridContainer.innerHTML = `ไม่สามารถดึงบทความอัตโนมัติได้ กรุณาตรวจสอบ REST API ของ WordPress
`; pagination.style.display = "none"; console.error(error); }); } let searchTimer; searchInput.addEventListener("input", function () { clearTimeout(searchTimer); searchTimer = setTimeout(() => { currentSearch = this.value; currentPage = 1; loadPosts(); }, 450); }); prevBtn.addEventListener("click", function () { if (currentPage > 1) { currentPage--; loadPosts(); document.querySelector(".co-blog-page").scrollIntoView({ behavior: "smooth" }); } }); nextBtn.addEventListener("click", function () { if (currentPage < totalPages) { currentPage++; loadPosts(); document.querySelector(".co-blog-page").scrollIntoView({ behavior: "smooth" }); } }); loadPosts(); } if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", initCoBlog); } else { initCoBlog(); } })(); =>