The WordPress REST API is a great thing, but in most cases you need to extend it. For example, if you use Advanced Custom Fields and you need to get them via the API, then you need to modify the response. Here’s a quick example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/** * Hook into the REST API and include featured_image in "wp-json/wp/v2/posts/" response * */ function slug_register_featured_img() { register_rest_field( 'post', 'featured_image', // Add it to the response array( 'get_callback' => 'get_featured_image_from_acf', // Callback function - returns the value 'update_callback' => null, 'schema' => null, ) ); } add_action( 'rest_api_init', 'slug_register_featured_img' ); /** * Get the value of the "image" ACF field * * @param array $object Details of current post. * @param string $field_name Name of field. * @param WP_REST_Request $request Current request * * @return mixed */ function get_featured_image_from_acf( $object, $field_name, $request ) { // Check if ACF plugin activated if ( function_exists( 'get_field' ) ) { // Get the value if ( $image = get_field('featured_image', $object['id'] ) ) : return wp_get_attachment_image_url($image, 'medium'); endif; } else { return ''; } } |