WordPress

WordPress REST API + Fetch – Xây Dựng Headless WordPress

WordPress REST API + Fetch – Xây Dựng Headless WordPress

WordPress REST API mở ra khả năng sử dụng WordPress như một headless CMS. Bài viết này hướng dẫn cách fetch data từ WordPress bằng JavaScript thuần.

Các Endpoint Quan Trọng

// Lấy tất cả posts
GET /wp-json/wp/v2/posts

// Lấy post theo ID
GET /wp-json/wp/v2/posts/1

// Lấy posts theo category
GET /wp-json/wp/v2/posts?categories=5

// Lấy posts có featured image
GET /wp-json/wp/v2/posts?_embed&per_page=10

Fetch Posts Với JavaScript

async function fetchPosts(categoryId = null, perPage = 10) {
    let url = `https://dev2.codenhanh.com/wp-json/wp/v2/posts?_embed&per_page=${perPage}`;
    
    if (categoryId) {
        url += `&categories=${categoryId}`;
    }
    
    try {
        const response = await fetch(url);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const posts = await response.json();
        
        return posts.map(post => ({
            id: post.id,
            title: post.title.rendered,
            excerpt: post.excerpt.rendered,
            date: new Date(post.date).toLocaleDateString('vi-VN'),
            featuredImage: post._embedded?.['wp:featuredmedia']?.[0]?.source_url || null,
            link: post.link,
        }));
        
    } catch (error) {
        console.error('Lỗi khi fetch posts:', error);
        return [];
    }
}

// Sử dụng
const posts = await fetchPosts(5, 6);
console.log(posts);

Thêm Custom Fields Vào REST API

// Trong functions.php
add_action('rest_api_init', function() {
    register_rest_field('post', 'reading_time', [
        'get_callback' => function($post) {
            $content = strip_tags($post['content']['rendered']);
            $word_count = str_word_count($content);
            return ceil($word_count / 200); // 200 từ/phút
        },
    ]);
});

REST API của WordPress rất mạnh. Hãy thêm authentication nếu cần truy cập dữ liệu private!

Bài viết liên quan