Skip to content

首页接口

类说明

Home 类提供首页相关的接口,目前主要提供最新文章列表功能,支持AJAX分页和分类筛选。

功能特点:

  • 支持分页加载
  • 支持按分类筛选
  • 返回渲染好的HTML片段
  • 遵循后台配置的分类显示规则

获取最新文章列表

Method : GET

URL : /wp-json/vtheme/v1/home/latest-posts

Auth required : False

Query Parameters :

  • page : [integer] 页码,默认1
  • category_id : [integer] 分类ID(可选),用于筛选特定分类的文章

Success Response

Code : 200 OK

Content example :

json
{
  "success": true,
  "html": "<article class=\"card\">...</article><article class=\"card\">...</article>",
  "current_page": 1,
  "total_pages": 10,
  "has_more": true
}

返回字段说明:

  • success : 请求是否成功
  • html : 渲染好的文章卡片HTML片段
  • current_page : 当前页码
  • total_pages : 总页数
  • has_more : 是否还有更多数据

Error Response

Code : 404 Not Found

Content example :

json
{
  "code": "no_posts",
  "message": "暂无文章",
  "data": {
    "status": 404
  }
}

使用示例

JavaScript Fetch API - 基础用法

javascript
// 获取第一页文章
fetch('/wp-json/vtheme/v1/home/latest-posts?page=1')
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      // 将HTML插入到页面
      document.getElementById('posts-container').innerHTML = data.html;
      
      console.log('当前页:', data.current_page);
      console.log('总页数:', data.total_pages);
      console.log('是否有更多:', data.has_more);
    }
  })
  .catch(error => {
    console.error('请求失败:', error);
  });

按分类筛选

javascript
// 获取分类ID为5的文章
fetch('/wp-json/vtheme/v1/home/latest-posts?page=1&category_id=5')
  .then(response => response.json())
  .then(data => {
    document.getElementById('posts-container').innerHTML = data.html;
  });

AJAX分页实现

javascript
let currentPage = 1;
let isLoading = false;

function loadPosts(page) {
  if (isLoading) return;
  
  isLoading = true;
  
  fetch(`/wp-json/vtheme/v1/home/latest-posts?page=${page}`)
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        const container = document.getElementById('posts-container');
        
        if (page === 1) {
          // 第一页替换内容
          container.innerHTML = data.html;
        } else {
          // 后续页追加内容
          container.insertAdjacentHTML('beforeend', data.html);
        }
        
        currentPage = data.current_page;
        
        // 如果还有更多,可以继续加载
        if (data.has_more) {
          console.log('还可以加载更多');
        } else {
          console.log('没有更多文章了');
        }
      }
      
      isLoading = false;
    })
    .catch(error => {
      console.error('加载失败:', error);
      isLoading = false;
    });
}

// 初始加载
loadPosts(1);

// 点击"加载更多"按钮
document.getElementById('load-more-btn').addEventListener('click', () => {
  loadPosts(currentPage + 1);
});

// 或者实现无限滚动
window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
    if (!isLoading && currentPage < totalPages) {
      loadPosts(currentPage + 1);
    }
  }
});

结合分类切换

javascript
// 分类切换
document.querySelectorAll('.category-filter').forEach(btn => {
  btn.addEventListener('click', (e) => {
    e.preventDefault();
    
    const categoryId = e.target.dataset.categoryId;
    currentPage = 1; // 重置页码
    
    let url = '/wp-json/vtheme/v1/home/latest-posts?page=1';
    if (categoryId) {
      url += `&category_id=${categoryId}`;
    }
    
    fetch(url)
      .then(response => response.json())
      .then(data => {
        document.getElementById('posts-container').innerHTML = data.html;
        currentPage = data.current_page;
      });
  });
});

注意事项

  1. HTML渲染

    • 接口返回的是已经渲染好的HTML片段
    • 可以直接插入到DOM中
    • 文章卡片模板位于 templates/card.php
  2. 分页逻辑

    • 第一页应该替换容器内容
    • 后续页应该追加到容器末尾
    • 使用 has_more 判断是否还有更多数据
  3. 分类筛选

    • 不传 category_id 时使用后台配置的默认分类规则
    • 传入 category_id 时只显示该分类的文章
    • 切换分类时应重置页码为1
  4. 性能优化

    • 建议实现防抖或节流避免频繁请求
    • 可以添加加载状态提示
    • 考虑缓存已加载的内容
  5. 错误处理

    • 当返回404时表示没有更多文章
    • 网络错误时需要给用户友好提示
    • 可以考虑添加重试机制