class-opengraph-oembed.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Frontend
  6. */
  7. /**
  8. * Class WPSEO_OpenGraph_OEmbed.
  9. */
  10. class WPSEO_OpenGraph_OEmbed implements WPSEO_WordPress_Integration {
  11. /**
  12. * Registers the hooks.
  13. */
  14. public function register_hooks() {
  15. // Check to make sure opengraph is enabled before adding filter.
  16. if ( WPSEO_Options::get( 'opengraph' ) ) {
  17. add_filter( 'oembed_response_data', [ $this, 'set_oembed_data' ], 10, 2 );
  18. }
  19. }
  20. /**
  21. * Callback function to pass to the oEmbed's response data that will enable
  22. * support for using the image and title set by the WordPress SEO plugin's fields. This
  23. * address the concern where some social channels/subscribed use oEmebed data over OpenGraph data
  24. * if both are present.
  25. *
  26. * @param array $data The oEmbed data.
  27. * @param WP_Post $post The current Post object.
  28. *
  29. * @link https://developer.wordpress.org/reference/hooks/oembed_response_data/ for hook info.
  30. *
  31. * @return array $filter_data - An array of oEmbed data with modified values where appropriate.
  32. */
  33. public function set_oembed_data( $data, $post ) {
  34. // Data to be returned.
  35. $filter_data = $data;
  36. // Look for the Yoast meta values (image and title)...
  37. $opengraph_title = WPSEO_Meta::get_value( 'opengraph-title', $post->ID );
  38. $opengraph_image = WPSEO_Meta::get_value( 'opengraph-image', $post->ID );
  39. // If yoast has a title set, update oEmbed with Yoast's title.
  40. if ( ! empty( $opengraph_title ) ) {
  41. $filter_data['title'] = $opengraph_title;
  42. }
  43. // If WPSEO Image was _not_ set, return the `$filter_data` as it currently is.
  44. if ( empty( $opengraph_image ) ) {
  45. return $filter_data;
  46. }
  47. // Since the a WPSEO Image was set, update the oEmbed data with the Yoast Image's info.
  48. // Get the image's ID from a URL.
  49. $image_id = WPSEO_Image_Utils::get_attachment_by_url( $opengraph_image );
  50. // Get the image's info from it's ID.
  51. $image_info = wp_get_attachment_metadata( $image_id );
  52. // Update the oEmbed data.
  53. $filter_data['thumbnail_url'] = $opengraph_image;
  54. if ( ! empty( $image_info['height'] ) ) {
  55. $filter_data['thumbnail_height'] = $image_info['height'];
  56. }
  57. if ( ! empty( $image_info['width'] ) ) {
  58. $filter_data['thumbnail_width'] = $image_info['width'];
  59. }
  60. return $filter_data;
  61. }
  62. }