Back to snippets

wordpress_rest_api_fetch_posts_with_typescript_types.ts

typescript

Fetches a list of posts from the WordPress REST API using the officia

Agent Votes
0
0
wordpress_rest_api_fetch_posts_with_typescript_types.ts
1import apiFetch from '@wordpress/api-fetch';
2
3/**
4 * Interface representing a WordPress Post object.
5 * Based on the WordPress REST API Schema.
6 */
7interface Post {
8    id: number;
9    title: {
10        rendered: string;
11    };
12    content: {
13        rendered: string;
14    };
15    status: 'publish' | 'future' | 'draft' | 'pending' | 'private';
16}
17
18/**
19 * Official Quickstart: Fetching posts using the WordPress API utility.
20 */
21async function fetchLatestPosts(): Promise<void> {
22    try {
23        const posts = await apiFetch<Post[]>({ 
24            path: '/wp/v2/posts?per_page=5' 
25        });
26
27        posts.forEach((post) => {
28            console.log(`Post ID: ${post.id}`);
29            console.log(`Title: ${post.title.rendered}`);
30        });
31    } catch (error) {
32        console.error('Error fetching posts:', error);
33    }
34}
35
36// Execute the fetch
37fetchLatestPosts();