I just want to fetch WordPress blog URL, slug and feature image using rest API and fetch js method and show it on other websites.
For reference: https://coderharsh.in
1 Like
You can use the WordPress REST API endpoint /wp-json/wp/v2/posts with the _embed parameter to get featured images in a single request.
Here’s a working example:
javascript
async function fetchPosts(siteUrl) {
const response = await fetch(`${siteUrl}/wp-json/wp/v2/posts?_embed&per_page=6`);
const posts = await response.json();
return posts.map(post => ({
title: post.title.rendered,
slug: post.slug,
url: post.link,
featuredImage: post._embedded?.['wp:featuredmedia']?.[0]?.source_url || null
}));
}
// Usage
fetchPosts('https://coderharsh.in').then(posts => {
const container = document.getElementById('blog-posts');
posts.forEach(post => {
container.innerHTML += `
<a href="${post.url}">
${post.featuredImage ? `<img src="${post.featuredImage}" alt="${post.title}">` : ''}
<h3>${post.title}</h3>
</a>
`;
});
});
The key is ?_embed — without it you only get the featured image ID and would need a second API call. With _embed, WordPress includes the full media object in the response.
If you run into CORS issues on the other website, you’ll need to add this to your WordPress site’s functions.php:
php
add_action('init', function() {
header('Access-Control-Allow-Origin: https://your-other-site.com');
});
Or use a more robust approach with the rest_pre_serve_request filter.