← All changes
|
_inc/lib/core-api/wpcom-endpoints/sites-posts-featured-media-url.php
+64
-0
16.2-beta
→
16.3
View file →
| @@ -1,0 +1,64 @@ | ||
| 1 | +<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName | |
| 2 | +/** | |
| 3 | + * WPCOM Add Featured Media URL | |
| 4 | + * Adds `jetpack_featured_media_url` to post responses | |
| 5 | + * | |
| 6 | + * @package automattic/jetpack | |
| 7 | + */ | |
| 8 | + | |
| 9 | +if ( ! defined( 'ABSPATH' ) ) { | |
| 10 | + exit( 0 ); | |
| 11 | +} | |
| 12 | + | |
| 13 | +/** | |
| 14 | + * Add featured media url to API post responses. | |
| 15 | + */ | |
| 16 | +class WPCOM_REST_API_V2_Sites_Posts_Add_Featured_Media_URL { | |
| 17 | + /** | |
| 18 | + * Constructor. | |
| 19 | + */ | |
| 20 | + public function __construct() { | |
| 21 | + add_action( 'rest_api_init', array( $this, 'add_featured_media_url' ) ); | |
| 22 | + } | |
| 23 | + | |
| 24 | + /** | |
| 25 | + * Add featured media url to post responses. | |
| 26 | + */ | |
| 27 | + public function add_featured_media_url() { | |
| 28 | + register_rest_field( | |
| 29 | + 'post', | |
| 30 | + 'jetpack_featured_media_url', | |
| 31 | + array( | |
| 32 | + 'get_callback' => array( $this, 'get_featured_media_url' ), | |
| 33 | + 'update_callback' => null, | |
| 34 | + 'schema' => null, | |
| 35 | + ) | |
| 36 | + ); | |
| 37 | + } | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * Get featured media url. | |
| 41 | + * | |
| 42 | + * @param mixed $object What the endpoint returns. | |
| 43 | + * @param string $field_name Should always match `->field_name`. | |
| 44 | + * @param WP_REST_Request $request WP API request. | |
| 45 | + * | |
| 46 | + * @return string | |
| 47 | + */ | |
| 48 | + public function get_featured_media_url( $object, $field_name, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable | |
| 49 | + if ( ! isset( $object['id'] ) ) { | |
| 50 | + return ''; | |
| 51 | + } | |
| 52 | + | |
| 53 | + $featured_media_url = ''; | |
| 54 | + $image_attributes = wp_get_attachment_image_src( | |
| 55 | + get_post_thumbnail_id( $object['id'] ), | |
| 56 | + 'full' | |
| 57 | + ); | |
| 58 | + if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) { | |
| 59 | + $featured_media_url = (string) $image_attributes[0]; | |
| 60 | + } | |
| 61 | + return $featured_media_url; | |
| 62 | + } | |
| 63 | +} | |
| 64 | +wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Sites_Posts_Add_Featured_Media_URL' ); | |