Skip to main content

Function Signature

export async function fetchBlogPosts(perPage = 10): Promise<BlogPost[]>
Fetches blog posts from the WordPress CMS API endpoint. This function retrieves posts with embedded media and taxonomy data, then transforms them into the application’s BlogPost format.

Parameters

perPage
number
default:"10"
The number of blog posts to retrieve per request. Optional parameter that defaults to 10 posts.

Return Type

BlogPost[]
Promise<BlogPost[]>
Returns a Promise that resolves to an array of blog post objects.

Behavior

  • Makes a GET request to the WordPress REST API /posts endpoint
  • Includes _embed parameter to fetch related media and taxonomy data
  • Strips HTML tags from title and excerpt fields
  • Formats dates using Spanish locale (es-ES)
  • Provides fallback placeholder image if featured media is not available
  • Throws an error if the API request fails

Error Handling

Throws an error with the format:
throw new Error(`WordPress API error: ${res.status}`);

Usage Example

Basic Usage (Default 10 Posts)

import { fetchBlogPosts } from '../lib/wordpress';
import { BlogPost } from '../types';

const [posts, setPosts] = useState<BlogPost[]>([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
  fetchBlogPosts()
    .then((wpPosts) => {
      if (wpPosts.length > 0) setPosts(wpPosts);
    })
    .catch((err) => console.warn('Error fetching WP posts, using fallback:', err))
    .finally(() => setLoading(false));
}, []);

Custom Number of Posts

import { fetchBlogPosts } from '../lib/wordpress';

// Fetch 20 posts
const posts = await fetchBlogPosts(20);

With Error Handling

import { fetchBlogPosts } from '../lib/wordpress';

try {
  const posts = await fetchBlogPosts(15);
  console.log(`Fetched ${posts.length} blog posts`);
} catch (error) {
  console.error('Failed to fetch blog posts:', error);
  // Use fallback data or show error message
}

API Endpoint

The function connects to:
https://cms.gobigagency.co/vencol/wp-json/wp/v2/posts?per_page={perPage}&_embed

Build docs developers (and LLMs) love