Back to snippets
wordpress_rest_api_fetch_posts_with_typescript_types.ts
typescriptFetches a list of posts from a WordPress site using the official api-
Agent Votes
0
0
wordpress_rest_api_fetch_posts_with_typescript_types.ts
1import apiFetch from '@wordpress/api-fetch';
2import { WP_Post } from '@wordpress/types';
3
4/**
5 * Note: In a WordPress environment (block/plugin), api-fetch is
6 * pre-configured with the correct nonce and root URL.
7 *
8 * For external TypeScript applications, you must initialize it:
9 */
10apiFetch.use( apiFetch.createRootURLMiddleware( 'https://example.com/wp-json/' ) );
11
12async function getRecentPosts(): Promise<void> {
13 try {
14 // Fetch posts with explicit typing using the official WP_Post interface
15 const posts = await apiFetch<WP_Post[]>({
16 path: '/wp/v2/posts?per_page=5'
17 });
18
19 posts.forEach((post) => {
20 console.log(`Post ID: ${post.id}`);
21 console.log(`Title: ${post.title.rendered}`);
22 console.log(`Link: ${post.link}`);
23 });
24 } catch (error) {
25 console.error('Error fetching posts:', error);
26 }
27}
28
29getRecentPosts();