[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> embed.php (source)

   1  <?php
   2  /**
   3   * oEmbed API: Top-level oEmbed functionality
   4   *
   5   * @package WordPress
   6   * @subpackage oEmbed
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Registers an embed handler.
  12   *
  13   * Should probably only be used for sites that do not support oEmbed.
  14   *
  15   * @since 2.9.0
  16   *
  17   * @global WP_Embed $wp_embed WordPress Embed object.
  18   *
  19   * @param string   $id       An internal ID/name for the handler. Needs to be unique.
  20   * @param string   $regex    The regex that will be used to see if this handler should be used for a URL.
  21   * @param callable $callback The callback function that will be called if the regex is matched.
  22   * @param int      $priority Optional. Used to specify the order in which the registered handlers will
  23   *                           be tested. Default 10.
  24   */
  25  function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  26      global $wp_embed;
  27      $wp_embed->register_handler( $id, $regex, $callback, $priority );
  28  }
  29  
  30  /**
  31   * Unregisters a previously-registered embed handler.
  32   *
  33   * @since 2.9.0
  34   *
  35   * @global WP_Embed $wp_embed WordPress Embed object.
  36   *
  37   * @param string $id       The handler ID that should be removed.
  38   * @param int    $priority Optional. The priority of the handler to be removed. Default 10.
  39   */
  40  function wp_embed_unregister_handler( $id, $priority = 10 ) {
  41      global $wp_embed;
  42      $wp_embed->unregister_handler( $id, $priority );
  43  }
  44  
  45  /**
  46   * Creates default array of embed parameters.
  47   *
  48   * The width defaults to the content width as specified by the theme. If the
  49   * theme does not specify a content width, then 500px is used.
  50   *
  51   * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  52   *
  53   * The {@see 'embed_defaults'} filter can be used to adjust either of these values.
  54   *
  55   * @since 2.9.0
  56   *
  57   * @global int $content_width
  58   *
  59   * @param string $url Optional. The URL that should be embedded. Default empty.
  60   * @return int[] {
  61   *     Indexed array of the embed width and height in pixels.
  62   *
  63   *     @type int $0 The embed width.
  64   *     @type int $1 The embed height.
  65   * }
  66   */
  67  function wp_embed_defaults( $url = '' ) {
  68      if ( ! empty( $GLOBALS['content_width'] ) ) {
  69          $width = (int) $GLOBALS['content_width'];
  70      }
  71  
  72      if ( empty( $width ) ) {
  73          $width = 500;
  74      }
  75  
  76      $height = min( (int) ceil( $width * 1.5 ), 1000 );
  77  
  78      /**
  79       * Filters the default array of embed dimensions.
  80       *
  81       * @since 2.9.0
  82       *
  83       * @param int[]  $size {
  84       *     Indexed array of the embed width and height in pixels.
  85       *
  86       *     @type int $0 The embed width.
  87       *     @type int $1 The embed height.
  88       * }
  89       * @param string $url  The URL that should be embedded.
  90       */
  91      return apply_filters( 'embed_defaults', compact( 'width', 'height' ), $url );
  92  }
  93  
  94  /**
  95   * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  96   *
  97   * @since 2.9.0
  98   *
  99   * @see WP_oEmbed
 100   *
 101   * @param string $url  The URL that should be embedded.
 102   * @param array|string $args {
 103   *     Optional. Additional arguments for retrieving embed HTML. Default empty.
 104   *
 105   *     @type int|string $width    Optional. The `maxwidth` value passed to the provider URL.
 106   *     @type int|string $height   Optional. The `maxheight` value passed to the provider URL.
 107   *     @type bool       $discover Optional. Determines whether to attempt to discover link tags
 108   *                                at the given URL for an oEmbed provider when the provider URL
 109   *                                is not found in the built-in providers list. Default true.
 110   * }
 111   * @return string|false The embed HTML on success, false on failure.
 112   */
 113  function wp_oembed_get( $url, $args = '' ) {
 114      $oembed = _wp_oembed_get_object();
 115      return $oembed->get_html( $url, $args );
 116  }
 117  
 118  /**
 119   * Returns the initialized WP_oEmbed object.
 120   *
 121   * @since 2.9.0
 122   * @access private
 123   *
 124   * @return WP_oEmbed object.
 125   */
 126  function _wp_oembed_get_object() {
 127      static $wp_oembed = null;
 128  
 129      if ( is_null( $wp_oembed ) ) {
 130          $wp_oembed = new WP_oEmbed();
 131      }
 132      return $wp_oembed;
 133  }
 134  
 135  /**
 136   * Adds a URL format and oEmbed provider URL pair.
 137   *
 138   * @since 2.9.0
 139   *
 140   * @see WP_oEmbed
 141   *
 142   * @param string $format   The format of URL that this provider can handle. You can use asterisks
 143   *                         as wildcards.
 144   * @param string $provider The URL to the oEmbed provider.
 145   * @param bool   $regex    Optional. Whether the `$format` parameter is in a RegEx format. Default false.
 146   */
 147  function wp_oembed_add_provider( $format, $provider, $regex = false ) {
 148      if ( did_action( 'plugins_loaded' ) ) {
 149          $oembed                       = _wp_oembed_get_object();
 150          $oembed->providers[ $format ] = array( $provider, $regex );
 151      } else {
 152          WP_oEmbed::_add_provider_early( $format, $provider, $regex );
 153      }
 154  }
 155  
 156  /**
 157   * Removes an oEmbed provider.
 158   *
 159   * @since 3.5.0
 160   *
 161   * @see WP_oEmbed
 162   *
 163   * @param string $format The URL format for the oEmbed provider to remove.
 164   * @return bool Was the provider removed successfully?
 165   */
 166  function wp_oembed_remove_provider( $format ) {
 167      if ( did_action( 'plugins_loaded' ) ) {
 168          $oembed = _wp_oembed_get_object();
 169  
 170          if ( isset( $oembed->providers[ $format ] ) ) {
 171              unset( $oembed->providers[ $format ] );
 172              return true;
 173          }
 174      } else {
 175          WP_oEmbed::_remove_provider_early( $format );
 176      }
 177  
 178      return false;
 179  }
 180  
 181  /**
 182   * Determines if default embed handlers should be loaded.
 183   *
 184   * Checks to make sure that the embeds library hasn't already been loaded. If
 185   * it hasn't, then it will load the embeds library.
 186   *
 187   * @since 2.9.0
 188   *
 189   * @see wp_embed_register_handler()
 190   */
 191  function wp_maybe_load_embeds() {
 192      /**
 193       * Filters whether to load the default embed handlers.
 194       *
 195       * Returning a falsey value will prevent loading the default embed handlers.
 196       *
 197       * @since 2.9.0
 198       *
 199       * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
 200       */
 201      if ( ! apply_filters( 'load_default_embeds', true ) ) {
 202          return;
 203      }
 204  
 205      wp_embed_register_handler( 'youtube_embed_url', '#https?://(www\.)?youtube\.com/(?:v|embed)/([^/]+)#i', 'wp_embed_handler_youtube' );
 206  
 207      /**
 208       * Filters the audio embed handler callback.
 209       *
 210       * @since 3.6.0
 211       *
 212       * @param callable $handler Audio embed handler callback function.
 213       */
 214      wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . implode( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
 215  
 216      /**
 217       * Filters the video embed handler callback.
 218       *
 219       * @since 3.6.0
 220       *
 221       * @param callable $handler Video embed handler callback function.
 222       */
 223      wp_embed_register_handler( 'video', '#^https?://.+?\.(' . implode( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
 224  }
 225  
 226  /**
 227   * YouTube iframe embed handler callback.
 228   *
 229   * Catches YouTube iframe embed URLs that are not parsable by oEmbed but can be translated into a URL that is.
 230   *
 231   * @since 4.0.0
 232   *
 233   * @global WP_Embed $wp_embed WordPress Embed object.
 234   *
 235   * @param array  $matches The RegEx matches from the provided regex when calling
 236   *                        wp_embed_register_handler().
 237   * @param array  $attr    Embed attributes.
 238   * @param string $url     The original URL that was matched by the regex.
 239   * @param array  $rawattr The original unmodified attributes.
 240   * @return string The embed HTML.
 241   */
 242  function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
 243      global $wp_embed;
 244      $embed = $wp_embed->autoembed( sprintf( 'https://youtube.com/watch?v=%s', urlencode( $matches[2] ) ) );
 245  
 246      /**
 247       * Filters the YouTube embed output.
 248       *
 249       * @since 4.0.0
 250       *
 251       * @see wp_embed_handler_youtube()
 252       *
 253       * @param string $embed   YouTube embed output.
 254       * @param array  $attr    An array of embed attributes.
 255       * @param string $url     The original URL that was matched by the regex.
 256       * @param array  $rawattr The original unmodified attributes.
 257       */
 258      return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
 259  }
 260  
 261  /**
 262   * Audio embed handler callback.
 263   *
 264   * @since 3.6.0
 265   *
 266   * @param array  $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
 267   * @param array  $attr Embed attributes.
 268   * @param string $url The original URL that was matched by the regex.
 269   * @param array  $rawattr The original unmodified attributes.
 270   * @return string The embed HTML.
 271   */
 272  function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
 273      $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
 274  
 275      /**
 276       * Filters the audio embed output.
 277       *
 278       * @since 3.6.0
 279       *
 280       * @param string $audio   Audio embed output.
 281       * @param array  $attr    An array of embed attributes.
 282       * @param string $url     The original URL that was matched by the regex.
 283       * @param array  $rawattr The original unmodified attributes.
 284       */
 285      return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
 286  }
 287  
 288  /**
 289   * Video embed handler callback.
 290   *
 291   * @since 3.6.0
 292   *
 293   * @param array  $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
 294   * @param array  $attr    Embed attributes.
 295   * @param string $url     The original URL that was matched by the regex.
 296   * @param array  $rawattr The original unmodified attributes.
 297   * @return string The embed HTML.
 298   */
 299  function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
 300      $dimensions = '';
 301      if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
 302          $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
 303          $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
 304      }
 305      $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
 306  
 307      /**
 308       * Filters the video embed output.
 309       *
 310       * @since 3.6.0
 311       *
 312       * @param string $video   Video embed output.
 313       * @param array  $attr    An array of embed attributes.
 314       * @param string $url     The original URL that was matched by the regex.
 315       * @param array  $rawattr The original unmodified attributes.
 316       */
 317      return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
 318  }
 319  
 320  /**
 321   * Registers the oEmbed REST API route.
 322   *
 323   * @since 4.4.0
 324   */
 325  function wp_oembed_register_route() {
 326      $controller = new WP_oEmbed_Controller();
 327      $controller->register_routes();
 328  }
 329  
 330  /**
 331   * Adds oEmbed discovery links in the head element of the website.
 332   *
 333   * @since 4.4.0
 334   * @since 6.8.0 Output was adjusted to only embed if the post supports it.
 335   * @since 6.9.0 Now runs first at `wp_head` priority 4, with a fallback to priority 10. This helps ensure the discovery links appear within the first 150KB.
 336   */
 337  function wp_oembed_add_discovery_links() {
 338      if ( doing_action( 'wp_head' ) ) {
 339          // For back-compat, short-circuit if a plugin has removed the action at the original priority.
 340          if ( ! has_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 ) ) {
 341              return;
 342          }
 343  
 344          // Prevent running again at the original priority.
 345          remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
 346      }
 347  
 348      $output = '';
 349  
 350      if ( is_singular() && is_post_embeddable() ) {
 351          $output .= '<link rel="alternate" title="' . _x( 'oEmbed (JSON)', 'oEmbed resource link name' ) . '" type="application/json+oembed" href="' . esc_url( get_oembed_endpoint_url( get_permalink() ) ) . '" />' . "\n";
 352  
 353          if ( class_exists( 'SimpleXMLElement' ) ) {
 354              $output .= '<link rel="alternate" title="' . _x( 'oEmbed (XML)', 'oEmbed resource link name' ) . '" type="text/xml+oembed" href="' . esc_url( get_oembed_endpoint_url( get_permalink(), 'xml' ) ) . '" />' . "\n";
 355          }
 356      }
 357  
 358      /**
 359       * Filters the oEmbed discovery links HTML.
 360       *
 361       * @since 4.4.0
 362       *
 363       * @param string $output HTML of the discovery links.
 364       */
 365      echo apply_filters( 'oembed_discovery_links', $output );
 366  }
 367  
 368  /**
 369   * Adds the necessary JavaScript to communicate with the embedded iframes.
 370   *
 371   * This function is no longer used directly. For back-compat it exists exclusively as a way to indicate that the oEmbed
 372   * host JS _should_ be added. In `default-filters.php` there remains this code:
 373   *
 374   *     add_action( 'wp_head', 'wp_oembed_add_host_js' )
 375   *
 376   * Historically a site has been able to disable adding the oEmbed host script by doing:
 377   *
 378   *     remove_action( 'wp_head', 'wp_oembed_add_host_js' )
 379   *
 380   * In order to ensure that such code still works as expected, this function remains. There is now a `has_action()` check
 381   * in `wp_maybe_enqueue_oembed_host_js()` to see if `wp_oembed_add_host_js()` has not been unhooked from running at the
 382   * `wp_head` action.
 383   *
 384   * @since 4.4.0
 385   * @deprecated 5.9.0 Use {@see wp_maybe_enqueue_oembed_host_js()} instead.
 386   */
 387  function wp_oembed_add_host_js() {}
 388  
 389  /**
 390   * Enqueue the wp-embed script if the provided oEmbed HTML contains a post embed.
 391   *
 392   * In order to only enqueue the wp-embed script on pages that actually contain post embeds, this function checks if the
 393   * provided HTML contains post embed markup and if so enqueues the script so that it will get printed in the footer.
 394   *
 395   * @since 5.9.0
 396   *
 397   * @param string $html Embed markup.
 398   * @return string Embed markup (without modifications).
 399   */
 400  function wp_maybe_enqueue_oembed_host_js( $html ) {
 401      if (
 402          has_action( 'wp_head', 'wp_oembed_add_host_js' )
 403          &&
 404          preg_match( '/<blockquote\s[^>]*?wp-embedded-content/', $html )
 405      ) {
 406          wp_enqueue_script( 'wp-embed' );
 407      }
 408      return $html;
 409  }
 410  
 411  /**
 412   * Retrieves the URL to embed a specific post in an iframe.
 413   *
 414   * @since 4.4.0
 415   *
 416   * @param int|WP_Post|null $post Optional. Post ID or object. Defaults to the current post.
 417   * @return string|false The post embed URL on success, false if the post doesn't exist.
 418   */
 419  function get_post_embed_url( $post = null ) {
 420      $post = get_post( $post );
 421  
 422      if ( ! $post ) {
 423          return false;
 424      }
 425  
 426      $embed_url     = trailingslashit( get_permalink( $post ) ) . user_trailingslashit( 'embed' );
 427      $path_conflict = get_page_by_path( str_replace( home_url(), '', $embed_url ), OBJECT, get_post_types( array( 'public' => true ) ) );
 428  
 429      if ( ! get_option( 'permalink_structure' ) || $path_conflict ) {
 430          $embed_url = add_query_arg( array( 'embed' => 'true' ), get_permalink( $post ) );
 431      }
 432  
 433      /**
 434       * Filters the URL to embed a specific post.
 435       *
 436       * @since 4.4.0
 437       *
 438       * @param string  $embed_url The post embed URL.
 439       * @param WP_Post $post      The corresponding post object.
 440       */
 441      return sanitize_url( apply_filters( 'post_embed_url', $embed_url, $post ) );
 442  }
 443  
 444  /**
 445   * Retrieves the oEmbed endpoint URL for a given permalink.
 446   *
 447   * Pass an empty string as the first argument to get the endpoint base URL.
 448   *
 449   * @since 4.4.0
 450   *
 451   * @param string $permalink Optional. The permalink used for the `url` query arg. Default empty.
 452   * @param string $format    Optional. The requested response format. Default 'json'.
 453   * @return string The oEmbed endpoint URL.
 454   */
 455  function get_oembed_endpoint_url( $permalink = '', $format = 'json' ) {
 456      $url = rest_url( 'oembed/1.0/embed' );
 457  
 458      if ( '' !== $permalink ) {
 459          $url = add_query_arg(
 460              array(
 461                  'url'    => urlencode( $permalink ),
 462                  'format' => ( 'json' !== $format ) ? $format : false,
 463              ),
 464              $url
 465          );
 466      }
 467  
 468      /**
 469       * Filters the oEmbed endpoint URL.
 470       *
 471       * @since 4.4.0
 472       *
 473       * @param string $url       The URL to the oEmbed endpoint.
 474       * @param string $permalink The permalink used for the `url` query arg.
 475       * @param string $format    The requested response format.
 476       */
 477      return apply_filters( 'oembed_endpoint_url', $url, $permalink, $format );
 478  }
 479  
 480  /**
 481   * Retrieves the embed code for a specific post.
 482   *
 483   * @since 4.4.0
 484   *
 485   * @param int              $width  The width for the response.
 486   * @param int              $height The height for the response.
 487   * @param int|WP_Post|null $post   Optional. Post ID or object. Default is global `$post`.
 488   * @return string|false Embed code on success, false if post doesn't exist.
 489   */
 490  function get_post_embed_html( $width, $height, $post = null ) {
 491      $post = get_post( $post );
 492  
 493      if ( ! $post ) {
 494          return false;
 495      }
 496  
 497      $embed_url = get_post_embed_url( $post );
 498  
 499      $secret     = wp_generate_password( 10, false );
 500      $embed_url .= "#?secret={$secret}";
 501  
 502      $output = sprintf(
 503          '<blockquote class="wp-embedded-content" data-secret="%1$s"><a href="%2$s">%3$s</a></blockquote>',
 504          esc_attr( $secret ),
 505          esc_url( get_permalink( $post ) ),
 506          get_the_title( $post )
 507      );
 508  
 509      $output .= sprintf(
 510          '<iframe sandbox="allow-scripts" security="restricted" src="%1$s" width="%2$d" height="%3$d" title="%4$s" data-secret="%5$s" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" class="wp-embedded-content"></iframe>',
 511          esc_url( $embed_url ),
 512          absint( $width ),
 513          absint( $height ),
 514          esc_attr(
 515              sprintf(
 516                  /* translators: 1: Post title, 2: Site title. */
 517                  __( '&#8220;%1$s&#8221; &#8212; %2$s' ),
 518                  get_the_title( $post ),
 519                  get_bloginfo( 'name' )
 520              )
 521          ),
 522          esc_attr( $secret )
 523      );
 524  
 525      /*
 526       * Note that the script must be placed after the <blockquote> and <iframe> due to a regexp parsing issue in
 527       * `wp_filter_oembed_result()`. Because of the regex pattern starts with `|(<blockquote>.*?</blockquote>)?.*|`
 528       * wherein the <blockquote> is marked as being optional, if it is not at the beginning of the string then the group
 529       * will fail to match and everything will be matched by `.*` and not included in the group. This regex issue goes
 530       * back to WordPress 4.4, so in order to not break older installs this script must come at the end.
 531       */
 532      $js_path = '/js/wp-embed' . wp_scripts_get_suffix() . '.js';
 533      $output .= wp_get_inline_script_tag(
 534          trim( file_get_contents( ABSPATH . WPINC . $js_path ) ) . "\n//# sourceURL=" . esc_url_raw( includes_url( $js_path ) )
 535      );
 536  
 537      /**
 538       * Filters the embed HTML output for a given post.
 539       *
 540       * @since 4.4.0
 541       *
 542       * @param string  $output The default iframe tag to display embedded content.
 543       * @param WP_Post $post   Current post object.
 544       * @param int     $width  Width of the response.
 545       * @param int     $height Height of the response.
 546       */
 547      return apply_filters( 'embed_html', $output, $post, $width, $height );
 548  }
 549  
 550  /**
 551   * Retrieves the oEmbed response data for a given post.
 552   *
 553   * @since 4.4.0
 554   * @since 6.8.0 Output was adjusted to only embed if the post type supports it.
 555   *
 556   * @param WP_Post|int $post  Post ID or post object.
 557   * @param int         $width The requested width.
 558   * @return array|false Response data on success, false if post doesn't exist,
 559   *                     is not publicly viewable or post type is not embeddable.
 560   */
 561  function get_oembed_response_data( $post, $width ) {
 562      $post  = get_post( $post );
 563      $width = absint( $width );
 564  
 565      if ( ! $post ) {
 566          return false;
 567      }
 568  
 569      if ( ! is_post_publicly_viewable( $post ) ) {
 570          return false;
 571      }
 572  
 573      if ( ! is_post_embeddable( $post ) ) {
 574          return false;
 575      }
 576  
 577      /**
 578       * Filters the allowed minimum and maximum widths for the oEmbed response.
 579       *
 580       * @since 4.4.0
 581       *
 582       * @param array $min_max_width {
 583       *     Minimum and maximum widths for the oEmbed response.
 584       *
 585       *     @type int $min Minimum width. Default 200.
 586       *     @type int $max Maximum width. Default 600.
 587       * }
 588       */
 589      $min_max_width = apply_filters(
 590          'oembed_min_max_width',
 591          array(
 592              'min' => 200,
 593              'max' => 600,
 594          )
 595      );
 596  
 597      $width  = min( max( $min_max_width['min'], $width ), $min_max_width['max'] );
 598      $height = max( (int) ceil( $width / 16 * 9 ), 200 );
 599  
 600      $data = array(
 601          'version'       => '1.0',
 602          'provider_name' => get_bloginfo( 'name' ),
 603          'provider_url'  => get_home_url(),
 604          'author_name'   => get_bloginfo( 'name' ),
 605          'author_url'    => get_home_url(),
 606          'title'         => get_the_title( $post ),
 607          'type'          => 'link',
 608      );
 609  
 610      $author = get_userdata( $post->post_author );
 611  
 612      if ( $author ) {
 613          $data['author_name'] = $author->display_name;
 614          $data['author_url']  = get_author_posts_url( $author->ID );
 615      }
 616  
 617      /**
 618       * Filters the oEmbed response data.
 619       *
 620       * @since 4.4.0
 621       *
 622       * @param array   $data   The response data.
 623       * @param WP_Post $post   The post object.
 624       * @param int     $width  The requested width.
 625       * @param int     $height The calculated height.
 626       */
 627      return apply_filters( 'oembed_response_data', $data, $post, $width, $height );
 628  }
 629  
 630  
 631  /**
 632   * Retrieves the oEmbed response data for a given URL.
 633   *
 634   * @since 5.0.0
 635   *
 636   * @param string $url  The URL that should be inspected for discovery `<link>` tags.
 637   * @param array  $args oEmbed remote get arguments.
 638   * @return object|false oEmbed response data if the URL does belong to the current site. False otherwise.
 639   */
 640  function get_oembed_response_data_for_url( $url, $args ) {
 641      $switched_blog = false;
 642  
 643      if ( is_multisite() ) {
 644          $url_parts = wp_parse_args(
 645              wp_parse_url( $url ),
 646              array(
 647                  'host' => '',
 648                  'port' => null,
 649                  'path' => '/',
 650              )
 651          );
 652  
 653          $qv = array(
 654              'domain'                 => $url_parts['host'] . ( $url_parts['port'] ? ':' . $url_parts['port'] : '' ),
 655              'path'                   => '/',
 656              'update_site_meta_cache' => false,
 657          );
 658  
 659          // In case of subdirectory configs, set the path.
 660          if ( ! is_subdomain_install() ) {
 661              $path = explode( '/', ltrim( $url_parts['path'], '/' ) );
 662              $path = reset( $path );
 663  
 664              if ( $path ) {
 665                  $qv['path'] = get_network()->path . $path . '/';
 666              }
 667          }
 668  
 669          $sites = get_sites( $qv );
 670          $site  = reset( $sites );
 671  
 672          // Do not allow embeds for deleted/archived/spam sites.
 673          if ( ! empty( $site->deleted ) || ! empty( $site->spam ) || ! empty( $site->archived ) ) {
 674              return false;
 675          }
 676  
 677          if ( $site && get_current_blog_id() !== (int) $site->blog_id ) {
 678              switch_to_blog( $site->blog_id );
 679              $switched_blog = true;
 680          }
 681      }
 682  
 683      $post_id = url_to_postid( $url );
 684  
 685      /** This filter is documented in wp-includes/class-wp-oembed-controller.php */
 686      $post_id = apply_filters( 'oembed_request_post_id', $post_id, $url );
 687  
 688      if ( ! $post_id ) {
 689          if ( $switched_blog ) {
 690              restore_current_blog();
 691          }
 692  
 693          return false;
 694      }
 695  
 696      $width = $args['width'] ?? 0;
 697  
 698      $data = get_oembed_response_data( $post_id, $width );
 699  
 700      if ( $switched_blog ) {
 701          restore_current_blog();
 702      }
 703  
 704      return $data ? (object) $data : false;
 705  }
 706  
 707  
 708  /**
 709   * Filters the oEmbed response data to return an iframe embed code.
 710   *
 711   * @since 4.4.0
 712   *
 713   * @param array   $data   The response data.
 714   * @param WP_Post $post   The post object.
 715   * @param int     $width  The requested width.
 716   * @param int     $height The calculated height.
 717   * @return array The modified response data.
 718   */
 719  function get_oembed_response_data_rich( $data, $post, $width, $height ) {
 720      $data['width']  = absint( $width );
 721      $data['height'] = absint( $height );
 722      $data['type']   = 'rich';
 723      $data['html']   = get_post_embed_html( $width, $height, $post );
 724  
 725      // Add post thumbnail to response if available.
 726      $thumbnail_id = false;
 727  
 728      if ( has_post_thumbnail( $post->ID ) ) {
 729          $thumbnail_id = get_post_thumbnail_id( $post->ID );
 730      }
 731  
 732      if ( 'attachment' === get_post_type( $post ) ) {
 733          if ( wp_attachment_is_image( $post ) ) {
 734              $thumbnail_id = $post->ID;
 735          } elseif ( wp_attachment_is( 'video', $post ) ) {
 736              $thumbnail_id = get_post_thumbnail_id( $post );
 737              $data['type'] = 'video';
 738          }
 739      }
 740  
 741      if ( $thumbnail_id ) {
 742          $thumbnail_src = wp_get_attachment_image_src( $thumbnail_id, array( $width, 0 ) );
 743  
 744          if ( is_array( $thumbnail_src ) ) {
 745              $data['thumbnail_url']    = $thumbnail_src[0];
 746              $data['thumbnail_width']  = $thumbnail_src[1];
 747              $data['thumbnail_height'] = $thumbnail_src[2];
 748          }
 749      }
 750  
 751      return $data;
 752  }
 753  
 754  /**
 755   * Ensures that the specified format is either 'json' or 'xml'.
 756   *
 757   * @since 4.4.0
 758   *
 759   * @param string $format The oEmbed response format. Accepts 'json' or 'xml'.
 760   * @return string The format, either 'xml' or 'json'. Default 'json'.
 761   */
 762  function wp_oembed_ensure_format( $format ) {
 763      if ( ! in_array( $format, array( 'json', 'xml' ), true ) ) {
 764          return 'json';
 765      }
 766  
 767      return $format;
 768  }
 769  
 770  /**
 771   * Hooks into the REST API output to print XML instead of JSON.
 772   *
 773   * This is only done for the oEmbed API endpoint,
 774   * which supports both formats.
 775   *
 776   * @access private
 777   * @since 4.4.0
 778   *
 779   * @param bool             $served  Whether the request has already been served.
 780   * @param WP_HTTP_Response $result  Result to send to the client. Usually a `WP_REST_Response`.
 781   * @param WP_REST_Request  $request Request used to generate the response.
 782   * @param WP_REST_Server   $server  Server instance.
 783   * @return bool True if the request was served, false otherwise.
 784   */
 785  function _oembed_rest_pre_serve_request( $served, $result, $request, $server ) {
 786      $params = $request->get_params();
 787  
 788      if ( '/oembed/1.0/embed' !== $request->get_route() || 'GET' !== $request->get_method() ) {
 789          return $served;
 790      }
 791  
 792      if ( ! isset( $params['format'] ) || 'xml' !== $params['format'] ) {
 793          return $served;
 794      }
 795  
 796      // Embed links inside the request.
 797      $data = $server->response_to_data( $result, false );
 798  
 799      if ( ! class_exists( 'SimpleXMLElement' ) ) {
 800          status_header( 501 );
 801          die( get_status_header_desc( 501 ) );
 802      }
 803  
 804      $result = _oembed_create_xml( $data );
 805  
 806      // Bail if there's no XML.
 807      if ( ! $result ) {
 808          status_header( 501 );
 809          die( get_status_header_desc( 501 ) );
 810      }
 811  
 812      if ( ! headers_sent() ) {
 813          $server->send_header( 'Content-Type', 'text/xml; charset=' . get_option( 'blog_charset' ) );
 814      }
 815  
 816      echo $result;
 817  
 818      return true;
 819  }
 820  
 821  /**
 822   * Creates an XML string from a given array.
 823   *
 824   * @since 4.4.0
 825   * @access private
 826   *
 827   * @param array            $data The original oEmbed response data.
 828   * @param SimpleXMLElement $node Optional. XML node to append the result to recursively.
 829   * @return string|false XML string on success, false on error.
 830   */
 831  function _oembed_create_xml( $data, $node = null ) {
 832      if ( ! is_array( $data ) || empty( $data ) ) {
 833          return false;
 834      }
 835  
 836      if ( null === $node ) {
 837          $node = new SimpleXMLElement( '<oembed></oembed>' );
 838      }
 839  
 840      foreach ( $data as $key => $value ) {
 841          if ( is_numeric( $key ) ) {
 842              $key = 'oembed';
 843          }
 844  
 845          if ( is_array( $value ) ) {
 846              $item = $node->addChild( $key );
 847              _oembed_create_xml( $value, $item );
 848          } else {
 849              $node->addChild( $key, esc_html( $value ) );
 850          }
 851      }
 852  
 853      return $node->asXML();
 854  }
 855  
 856  /**
 857   * Filters the given oEmbed HTML to make sure iframes have a title attribute.
 858   *
 859   * @since 5.2.0
 860   *
 861   * @param string|false $result The oEmbed HTML result.
 862   * @param object       $data   A data object result from an oEmbed provider.
 863   * @param string       $url    The URL of the content to be embedded.
 864   * @return string|false The filtered oEmbed result.
 865   */
 866  function wp_filter_oembed_iframe_title_attribute( $result, $data, $url ) {
 867      if ( false === $result || ! in_array( $data->type, array( 'rich', 'video' ), true ) ) {
 868          return $result;
 869      }
 870  
 871      $title = ! empty( $data->title ) ? $data->title : '';
 872  
 873      $pattern = '`<iframe([^>]*)>`i';
 874      if ( preg_match( $pattern, $result, $matches ) ) {
 875          $attrs = wp_kses_hair( $matches[1], wp_allowed_protocols() );
 876  
 877          foreach ( $attrs as $attr => $item ) {
 878              $lower_attr = strtolower( $attr );
 879              if ( $lower_attr === $attr ) {
 880                  continue;
 881              }
 882              if ( ! isset( $attrs[ $lower_attr ] ) ) {
 883                  $attrs[ $lower_attr ] = $item;
 884                  unset( $attrs[ $attr ] );
 885              }
 886          }
 887      }
 888  
 889      if ( ! empty( $attrs['title']['value'] ) ) {
 890          $title = $attrs['title']['value'];
 891      }
 892  
 893      /**
 894       * Filters the title attribute of the given oEmbed HTML iframe.
 895       *
 896       * @since 5.2.0
 897       *
 898       * @param string $title  The title attribute.
 899       * @param string $result The oEmbed HTML result.
 900       * @param object $data   A data object result from an oEmbed provider.
 901       * @param string $url    The URL of the content to be embedded.
 902       */
 903      $title = apply_filters( 'oembed_iframe_title_attribute', $title, $result, $data, $url );
 904  
 905      if ( '' === $title ) {
 906          return $result;
 907      }
 908  
 909      if ( isset( $attrs['title'] ) ) {
 910          unset( $attrs['title'] );
 911          $attr_string = implode( ' ', wp_list_pluck( $attrs, 'whole' ) );
 912          $result      = str_replace( $matches[0], '<iframe ' . trim( $attr_string ) . '>', $result );
 913      }
 914      return str_ireplace( '<iframe ', sprintf( '<iframe title="%s" ', esc_attr( $title ) ), $result );
 915  }
 916  
 917  
 918  /**
 919   * Filters the given oEmbed HTML.
 920   *
 921   * If the `$url` isn't on the trusted providers list,
 922   * we need to filter the HTML heavily for security.
 923   *
 924   * Only filters 'rich' and 'video' response types.
 925   *
 926   * @since 4.4.0
 927   *
 928   * @param string|false $result The oEmbed HTML result.
 929   * @param object       $data   A data object result from an oEmbed provider.
 930   * @param string       $url    The URL of the content to be embedded.
 931   * @return string|false The filtered and sanitized oEmbed result.
 932   */
 933  function wp_filter_oembed_result( $result, $data, $url ) {
 934      if ( false === $result || ! in_array( $data->type, array( 'rich', 'video' ), true ) ) {
 935          return $result;
 936      }
 937  
 938      $wp_oembed = _wp_oembed_get_object();
 939  
 940      // Don't modify the HTML for trusted providers.
 941      if ( false !== $wp_oembed->get_provider( $url, array( 'discover' => false ) ) ) {
 942          return $result;
 943      }
 944  
 945      $allowed_html = array(
 946          'a'          => array(
 947              'href' => true,
 948          ),
 949          'blockquote' => array(),
 950          'iframe'     => array(
 951              'src'          => true,
 952              'width'        => true,
 953              'height'       => true,
 954              'frameborder'  => true,
 955              'marginwidth'  => true,
 956              'marginheight' => true,
 957              'scrolling'    => true,
 958              'title'        => true,
 959          ),
 960      );
 961  
 962      $html = wp_kses( $result, $allowed_html );
 963  
 964      preg_match( '|(<blockquote>.*?</blockquote>)?.*(<iframe.*?></iframe>)|ms', $html, $content );
 965      // We require at least the iframe to exist.
 966      if ( empty( $content[2] ) ) {
 967          return false;
 968      }
 969      $html = $content[1] . $content[2];
 970  
 971      preg_match( '/ src=([\'"])(.*?)\1/', $html, $results );
 972  
 973      if ( ! empty( $results ) ) {
 974          $secret = wp_generate_password( 10, false );
 975  
 976          $url = esc_url( "{$results[2]}#?secret=$secret" );
 977          $q   = $results[1];
 978  
 979          $html = str_replace( $results[0], ' src=' . $q . $url . $q . ' data-secret=' . $q . $secret . $q, $html );
 980          $html = str_replace( '<blockquote', "<blockquote data-secret=\"$secret\"", $html );
 981      }
 982  
 983      $allowed_html['blockquote']['data-secret'] = true;
 984      $allowed_html['iframe']['data-secret']     = true;
 985  
 986      $html = wp_kses( $html, $allowed_html );
 987  
 988      if ( ! empty( $content[1] ) ) {
 989          // We have a blockquote to fall back on. Hide the iframe by default.
 990          $html = str_replace( '<iframe', '<iframe style="position: absolute; visibility: hidden;"', $html );
 991          $html = str_replace( '<blockquote', '<blockquote class="wp-embedded-content"', $html );
 992      }
 993  
 994      $html = str_ireplace( '<iframe', '<iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"', $html );
 995  
 996      return $html;
 997  }
 998  
 999  /**
1000   * Filters the string in the 'more' link displayed after a trimmed excerpt.
1001   *
1002   * Replaces '[...]' (appended to automatically generated excerpts) with an
1003   * ellipsis and a "Continue reading" link in the embed template.
1004   *
1005   * @since 4.4.0
1006   *
1007   * @param string $more_string Default 'more' string.
1008   * @return string 'Continue reading' link prepended with an ellipsis.
1009   */
1010  function wp_embed_excerpt_more( $more_string ) {
1011      if ( ! is_embed() ) {
1012          return $more_string;
1013      }
1014  
1015      $link = sprintf(
1016          '<a href="%1$s" class="wp-embed-more" target="_top">%2$s</a>',
1017          esc_url( get_permalink() ),
1018          /* translators: %s: Post title. */
1019          sprintf( __( 'Continue reading %s' ), '<span class="screen-reader-text">' . get_the_title() . '</span>' )
1020      );
1021      return ' &hellip; ' . $link;
1022  }
1023  
1024  /**
1025   * Displays the post excerpt for the embed template.
1026   *
1027   * Intended to be used in 'The Loop'.
1028   *
1029   * @since 4.4.0
1030   */
1031  function the_excerpt_embed() {
1032      $output = get_the_excerpt();
1033  
1034      /**
1035       * Filters the post excerpt for the embed template.
1036       *
1037       * @since 4.4.0
1038       *
1039       * @param string $output The current post excerpt.
1040       */
1041      echo apply_filters( 'the_excerpt_embed', $output );
1042  }
1043  
1044  /**
1045   * Filters the post excerpt for the embed template.
1046   *
1047   * Shows players for video and audio attachments.
1048   *
1049   * @since 4.4.0
1050   *
1051   * @param string $content The current post excerpt.
1052   * @return string The modified post excerpt.
1053   */
1054  function wp_embed_excerpt_attachment( $content ) {
1055      if ( is_attachment() ) {
1056          return prepend_attachment( '' );
1057      }
1058  
1059      return $content;
1060  }
1061  
1062  /**
1063   * Enqueues embed iframe default CSS and JS.
1064   *
1065   * Enqueue PNG fallback CSS for embed iframe for legacy versions of IE.
1066   *
1067   * Allows plugins to queue scripts for the embed iframe end using wp_enqueue_script().
1068   * Runs first in oembed_head().
1069   *
1070   * @since 4.4.0
1071   */
1072  function enqueue_embed_scripts() {
1073  
1074      /**
1075       * Fires when scripts and styles are enqueued for the embed iframe.
1076       *
1077       * @since 4.4.0
1078       */
1079      do_action( 'enqueue_embed_scripts' );
1080  }
1081  
1082  /**
1083   * Enqueues the CSS in the embed iframe header.
1084   *
1085   * @since 6.4.0
1086   */
1087  function wp_enqueue_embed_styles() {
1088      // Back-compat for plugins that disable functionality by unhooking this action.
1089      if ( ! has_action( 'embed_head', 'print_embed_styles' ) ) {
1090          return;
1091      }
1092      remove_action( 'embed_head', 'print_embed_styles' );
1093  
1094      $suffix = wp_scripts_get_suffix();
1095      $handle = 'wp-embed-template';
1096      wp_register_style( $handle, false );
1097      wp_add_inline_style( $handle, file_get_contents( ABSPATH . WPINC . "/css/wp-embed-template$suffix.css" ) );
1098      wp_enqueue_style( $handle );
1099  }
1100  
1101  /**
1102   * Prints the JavaScript in the embed iframe header.
1103   *
1104   * @since 4.4.0
1105   */
1106  function print_embed_scripts() {
1107      $js_path = '/js/wp-embed-template' . wp_scripts_get_suffix() . '.js';
1108      wp_print_inline_script_tag(
1109          trim( file_get_contents( ABSPATH . WPINC . $js_path ) ) . "\n//# sourceURL=" . esc_url_raw( includes_url( $js_path ) )
1110      );
1111  }
1112  
1113  /**
1114   * Prepare the oembed HTML to be displayed in an RSS feed.
1115   *
1116   * @since 4.4.0
1117   * @access private
1118   *
1119   * @param string $content The content to filter.
1120   * @return string The filtered content.
1121   */
1122  function _oembed_filter_feed_content( $content ) {
1123      $p = new WP_HTML_Tag_Processor( $content );
1124      while ( $p->next_tag( array( 'tag_name' => 'iframe' ) ) ) {
1125          if ( $p->has_class( 'wp-embedded-content' ) ) {
1126              $p->remove_attribute( 'style' );
1127          }
1128      }
1129      return $p->get_updated_html();
1130  }
1131  
1132  /**
1133   * Prints the necessary markup for the embed comments button.
1134   *
1135   * @since 4.4.0
1136   */
1137  function print_embed_comments_button() {
1138      if ( is_404() || ! ( get_comments_number() || comments_open() ) ) {
1139          return;
1140      }
1141      ?>
1142      <div class="wp-embed-comments">
1143          <a href="<?php comments_link(); ?>" target="_top">
1144              <span class="dashicons dashicons-admin-comments"></span>
1145              <?php
1146              printf(
1147                  /* translators: %s: Number of comments. */
1148                  _n(
1149                      '%s <span class="screen-reader-text">Comment</span>',
1150                      '%s <span class="screen-reader-text">Comments</span>',
1151                      get_comments_number()
1152                  ),
1153                  number_format_i18n( get_comments_number() )
1154              );
1155              ?>
1156          </a>
1157      </div>
1158      <?php
1159  }
1160  
1161  /**
1162   * Prints the necessary markup for the embed sharing button.
1163   *
1164   * @since 4.4.0
1165   */
1166  function print_embed_sharing_button() {
1167      if ( is_404() ) {
1168          return;
1169      }
1170      ?>
1171      <div class="wp-embed-share">
1172          <button type="button" class="wp-embed-share-dialog-open" aria-label="<?php esc_attr_e( 'Open sharing dialog' ); ?>">
1173              <span class="dashicons dashicons-share"></span>
1174          </button>
1175      </div>
1176      <?php
1177  }
1178  
1179  /**
1180   * Prints the necessary markup for the embed sharing dialog.
1181   *
1182   * @since 4.4.0
1183   */
1184  function print_embed_sharing_dialog() {
1185      if ( is_404() ) {
1186          return;
1187      }
1188  
1189      $unique_suffix            = get_the_ID() . '-' . wp_rand();
1190      $share_tab_wordpress_id   = 'wp-embed-share-tab-wordpress-' . $unique_suffix;
1191      $share_tab_html_id        = 'wp-embed-share-tab-html-' . $unique_suffix;
1192      $description_wordpress_id = 'wp-embed-share-description-wordpress-' . $unique_suffix;
1193      $description_html_id      = 'wp-embed-share-description-html-' . $unique_suffix;
1194      ?>
1195      <div class="wp-embed-share-dialog hidden" role="dialog" aria-label="<?php esc_attr_e( 'Sharing options' ); ?>">
1196          <div class="wp-embed-share-dialog-content">
1197              <div class="wp-embed-share-dialog-text">
1198                  <ul class="wp-embed-share-tabs" role="tablist">
1199                      <li class="wp-embed-share-tab-button wp-embed-share-tab-button-wordpress" role="presentation">
1200                          <button type="button" role="tab" aria-controls="<?php echo $share_tab_wordpress_id; ?>" aria-selected="true" tabindex="0"><?php esc_html_e( 'WordPress Embed' ); ?></button>
1201                      </li>
1202                      <li class="wp-embed-share-tab-button wp-embed-share-tab-button-html" role="presentation">
1203                          <button type="button" role="tab" aria-controls="<?php echo $share_tab_html_id; ?>" aria-selected="false" tabindex="-1"><?php esc_html_e( 'HTML Embed' ); ?></button>
1204                      </li>
1205                  </ul>
1206                  <div id="<?php echo $share_tab_wordpress_id; ?>" class="wp-embed-share-tab" role="tabpanel" aria-hidden="false">
1207                      <input type="text" value="<?php the_permalink(); ?>" class="wp-embed-share-input" aria-label="<?php esc_attr_e( 'URL' ); ?>" aria-describedby="<?php echo $description_wordpress_id; ?>" tabindex="0" readonly/>
1208  
1209                      <p class="wp-embed-share-description" id="<?php echo $description_wordpress_id; ?>">
1210                          <?php _e( 'Copy and paste this URL into your WordPress site to embed' ); ?>
1211                      </p>
1212                  </div>
1213                  <div id="<?php echo $share_tab_html_id; ?>" class="wp-embed-share-tab" role="tabpanel" aria-hidden="true">
1214                      <textarea class="wp-embed-share-input" aria-label="<?php esc_attr_e( 'HTML' ); ?>" aria-describedby="<?php echo $description_html_id; ?>" tabindex="0" readonly><?php echo esc_textarea( get_post_embed_html( 600, 400 ) ); ?></textarea>
1215  
1216                      <p class="wp-embed-share-description" id="<?php echo $description_html_id; ?>">
1217                          <?php _e( 'Copy and paste this code into your site to embed' ); ?>
1218                      </p>
1219                  </div>
1220              </div>
1221  
1222              <button type="button" class="wp-embed-share-dialog-close" aria-label="<?php esc_attr_e( 'Close sharing dialog' ); ?>">
1223                  <span class="dashicons dashicons-no"></span>
1224              </button>
1225          </div>
1226      </div>
1227      <?php
1228  }
1229  
1230  /**
1231   * Prints the necessary markup for the site title in an embed template.
1232   *
1233   * @since 4.5.0
1234   */
1235  function the_embed_site_title(): void {
1236      $fallback_icon_url = includes_url( 'images/w-logo-gray-white-bg.svg' );
1237      $site_icon_url     = get_site_icon_url( 32, $fallback_icon_url );
1238  
1239      $icon_img = '';
1240      if ( $site_icon_url ) {
1241          $site_icon_url_2x = get_site_icon_url( 64, $fallback_icon_url );
1242          $srcset           = ( $site_icon_url_2x && $site_icon_url !== $site_icon_url_2x ) ? sprintf( ' srcset="%s 2x"', esc_url( $site_icon_url_2x ) ) : '';
1243          $icon_img         = sprintf(
1244              '<img src="%s"%s width="32" height="32" alt="" class="wp-embed-site-icon" />',
1245              esc_url( $site_icon_url ),
1246              $srcset
1247          );
1248      }
1249  
1250      $site_title = sprintf(
1251          '<a href="%s" target="_top">%s<span>%s</span></a>',
1252          esc_url( home_url() ),
1253          $icon_img,
1254          esc_html( get_bloginfo( 'name' ) )
1255      );
1256  
1257      $site_title = '<div class="wp-embed-site-title">' . $site_title . '</div>';
1258  
1259      /**
1260       * Filters the site title HTML in the embed footer.
1261       *
1262       * @since 4.4.0
1263       *
1264       * @param string $site_title The site title HTML.
1265       */
1266      echo apply_filters( 'embed_site_title_html', $site_title );
1267  }
1268  
1269  /**
1270   * Filters the oEmbed result before any HTTP requests are made.
1271   *
1272   * If the URL belongs to the current site, the result is fetched directly instead of
1273   * going through the oEmbed discovery process.
1274   *
1275   * @since 4.5.3
1276   *
1277   * @param null|string $result The UNSANITIZED (and potentially unsafe) HTML that should be used to embed. Default null.
1278   * @param string      $url    The URL that should be inspected for discovery `<link>` tags.
1279   * @param array       $args   oEmbed remote get arguments.
1280   * @return null|string The UNSANITIZED (and potentially unsafe) HTML that should be used to embed.
1281   *                     Null if the URL does not belong to the current site.
1282   */
1283  function wp_filter_pre_oembed_result( $result, $url, $args ) {
1284      $data = get_oembed_response_data_for_url( $url, $args );
1285  
1286      if ( $data ) {
1287          return _wp_oembed_get_object()->data2html( $data, $url );
1288      }
1289  
1290      return $result;
1291  }


Generated : Wed Jul 1 08:20:12 2026 Cross-referenced by PHPXref