WP_oEmbed::discover()publicWP 2.9.0

Attempts to discover link tags at the given URL for an oEmbed provider.

Method of the class: WP_oEmbed{}

Return

String|false. The oEmbed provider URL on success, false on failure.

Usage

$WP_oEmbed = new WP_oEmbed();
$WP_oEmbed->discover( $url );
$url(string) (required)
The URL that should be inspected for discovery <link> tags.

Changelog

Since 2.9.0 Introduced.

WP_oEmbed::discover() code WP 6.4.3

public function discover( $url ) {
	$providers = array();
	$args      = array(
		'limit_response_size' => 153600, // 150 KB
	);

	/**
	 * Filters oEmbed remote get arguments.
	 *
	 * @since 4.0.0
	 *
	 * @see WP_Http::request()
	 *
	 * @param array  $args oEmbed remote get arguments.
	 * @param string $url  URL to be inspected.
	 */
	$args = apply_filters( 'oembed_remote_get_args', $args, $url );

	// Fetch URL content.
	$request = wp_safe_remote_get( $url, $args );
	$html    = wp_remote_retrieve_body( $request );
	if ( $html ) {

		/**
		 * Filters the link types that contain oEmbed provider URLs.
		 *
		 * @since 2.9.0
		 *
		 * @param string[] $format Array of oEmbed link types. Accepts 'application/json+oembed',
		 *                         'text/xml+oembed', and 'application/xml+oembed' (incorrect,
		 *                         used by at least Vimeo).
		 */
		$linktypes = apply_filters(
			'oembed_linktypes',
			array(
				'application/json+oembed' => 'json',
				'text/xml+oembed'         => 'xml',
				'application/xml+oembed'  => 'xml',
			)
		);

		// Strip <body>.
		$html_head_end = stripos( $html, '</head>' );
		if ( $html_head_end ) {
			$html = substr( $html, 0, $html_head_end );
		}

		// Do a quick check.
		$tagfound = false;
		foreach ( $linktypes as $linktype => $format ) {
			if ( stripos( $html, $linktype ) ) {
				$tagfound = true;
				break;
			}
		}

		if ( $tagfound && preg_match_all( '#<link([^<>]+)/?>#iU', $html, $links ) ) {
			foreach ( $links[1] as $link ) {
				$atts = shortcode_parse_atts( $link );

				if ( ! empty( $atts['type'] ) && ! empty( $linktypes[ $atts['type'] ] ) && ! empty( $atts['href'] ) ) {
					$providers[ $linktypes[ $atts['type'] ] ] = htmlspecialchars_decode( $atts['href'] );

					// Stop here if it's JSON (that's all we need).
					if ( 'json' === $linktypes[ $atts['type'] ] ) {
						break;
					}
				}
			}
		}
	}

	// JSON is preferred to XML.
	if ( ! empty( $providers['json'] ) ) {
		return $providers['json'];
	} elseif ( ! empty( $providers['xml'] ) ) {
		return $providers['xml'];
	} else {
		return false;
	}
}