How to Call a Custom WordPress REST API on the Front End

Using the Featured Image with URL plugin from the previous article as an example: If you want to replace the original WordPress featured image on the front end, you only need to locate the featured image secation in the template file. At the beginning of the template file PostLayout.astro, the named export getFeaturedImageUrl is imported from the module ../lib/wordpress. Next, we […]


Using the Featured Image with URL plugin from the previous article as an example: If you want to replace the original WordPress featured image on the front end, you only need to locate the featured image secation in the template file.

At the beginning of the template file PostLayout.astro, the named export getFeaturedImageUrl is imported from the module ../lib/wordpress. Next, we continue exploring the ../lib/wordpress directory.

Open the file ../lib/wordpress.js. In the exported object WPPost at the beginning of the file, you can find:

_embedded?: {
author?: WPAuthor[];
'wp:featuredmedia'?: WPMedia[];
'wp:term'?: WPTerm[][];
};

Go back to the WordPress REST API endpoint and check the same object. You will see that the Featured Image with URL plugin has added an extra field:

"meta": {
"_harikrutfiwu_url": "https://cdn.jsdelivr.net/gh/yyds/resource@main/img/059e4edf-cecf-4cd4-877b-48ee3b27a935.jpg",
"footnotes": ""
},

This is the part we need to add to the exported object. Remove the unnecessary "footnotes": "" from the code above, then paste the remaining part into the WPPost object. Remove the fixed image URL and change _harikrutfiwu_url to a string type. The complete code is as follows:

meta: {
_harikrutfiwu_url?: string;
};

This completes the data export step by retrieving the required field. Next, we need to display it where needed. In the exported function getFeaturedImageUrl at the bottom of the same file, change the declared variable:

const media = post._embedded?.['wp:featuredmedia']?.[0];

to:

const media = post.meta._harikrutfiwu_url;

Then return the value of the media variable. Since it is a string, this is very straightforward—just return media directly:

return media;

The function getFeaturedImageUrl will be imported in the template file PostLayout.astro. With this, we have completed the process of fetching a remote Featured Image URL on the front end.