When working with the WordPress REST API by adding custom fields for JSON response while creating custom REST API URL or not, it’s common to include the post thumbnail in the API response to provide additional visual information. One way to achieve this is by using the get_the_post_thumbnail_url()
function to fetch the URL of the post thumbnail. Let’s explore this concept further by delving into a specific example and breaking it down for clearer understanding.
Example: Including Post Thumbnail in REST API Response for Professors
Consider the following code snippet used in the context of sending post thumbnail as part of the REST API response for professors:
if(get_post_type() == 'professor') { array_push($results['professors'], array( 'name' => get_the_title(), 'permalink' => get_the_permalink(), 'image' => get_the_post_thumbnail_url(0, 'professorLandscape') )); }
In this example:
- The condition checks if the post type is ‘professor’.
- If the post is of type
'professor'
, it adds an array with'name'
(title),'permalink'
, and'image'
(post thumbnail URL for'professorLandscape'
size) to the ‘professors’ key in the$results
array.
Detailed Explanation:
- Condition Check: The
if(get_post_type() == 'professor')
statement ensures that the following actions are executed only for posts of the'professor'
type. - Adding Data to Results Array:
'name'
: Includes the title of the post using
.get_the_title()
'permalink'
: Retrieves the post permalink usingget_the_permalink()
.'image'
: Fetches the URL of the post thumbnail for the'professorLandscape'
size withget_the_post_thumbnail_url(0, 'professorLandscape')
This approach allows you to structure the API response with relevant information about professors, including their names, permalinks, and respective post thumbnail URLs for a specific thumbnail size.
By leveraging get_the_post_thumbnail_url()
effectively in your WordPress REST API responses, you can enrich the content with visually appealing elements, enhancing the overall user experience and engagement with the API data.