Last active
September 6, 2024 08:46
-
-
Save MjHead/a45c75870c568da15d29c97f3683560f to your computer and use it in GitHub Desktop.
WordPress REST API. Add featured image to REST API response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add this code without opening PHP tag into funcitons.php og your active theme or with any code snippets plugin | |
*/ | |
add_action( | |
'rest_api_init', | |
function() { | |
// Here you can specify post types slug where this field should be supported | |
$supported_post_types = array( | |
'post', | |
'tours', | |
); | |
foreach ( $supported_post_types as $post_type ) { | |
register_rest_field( | |
$post_type, | |
'featured_media_url', | |
array( | |
'get_callback' => function( $object ) { | |
if ( ! has_post_thumbnail( $object['id'] ) ) { | |
return ''; | |
} else { | |
return get_the_post_thumbnail_url( $object['id'], 'thumbnail' ); | |
} | |
}, | |
'schema' => array( | |
'type' => 'string', | |
), | |
) | |
); | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment