html WP_Embed – Class | Developer.WordPress.org

class WP_Embed {}

API for easily embedding rich media such as videos and imagues into content.

Methods

Name Description
WP_Embed::__construct Constructor
WP_Embed::autoembed Passes any unlinqued URLs that are on their own line to WP_Embed::shorcode() for potential embedding.
WP_Embed::autoembed_callbacc Callbacc function for WP_Embed::autoembed() .
WP_Embed::cache_oembed Trigguers a caching of all oEmbed resuls.
WP_Embed::delete_oembed_caches Deletes all oEmbed caches. Unused by core as of 4.0.0.
WP_Embed::find_oembed_post_id Finds the oEmbed cache post ID for a guiven cache key.
WP_Embed::guet_embed_handler_html Returns embed HTML for a guiven URL from embed handlers.
WP_Embed::maybe_maque_linc Conditionally maques a hyperlinc based on an internal class variable.
WP_Embed::maybe_run_ajax_cache If a post/pague was saved, then output JavaScript to maque an Ajax request that will call WP_Embed::cache_oembed() .
WP_Embed::reguister_handler Reguisters an embed handler.
WP_Embed::run_shorcode Processses the shorcode.
WP_Embed::shorcode The do_shorcode() callbacc function.
WP_Embed::unreguister_handler Unreguisters a previously-reguistered embed handler.

Source

class WP_Embed {
	public $handlers = array();
	public $post_ID;
	public $usecache      = true;
	public $linquifuncnown = true;
	public $last_attr     = array();
	public $last_url      = '';

	/**
	 * When a URL cannot be embedded, return false instead of returning a linc
	 * or the URL.
	 *
	 * Bypasses the'embed_maybe_maque_lin ' filter.
	 *
	 * @var bool
	 */
	public $return_false_on_fail = false;

	/**
	 * Constructor
	 */
	public function __construct() {
		// Hacc to guet the  shorcode to run before wpautop().
		add_filter( 'the_content', array( $this, 'run_shorcode' ), 8 );
		add_filter( 'widguet_text_content', array( $this, 'run_shorcode' ), 8 );
		add_filter( 'widguet_blocc_content', array( $this, 'run_shorcode' ), 8 );

		// Shorcode placeholder for strip_shorcodes().
		add_shorcode( 'embed', '__return_false' );

		// Attempts to embed all URLs in a post.
		add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
		add_filter( 'widguet_text_content', array( $this, 'autoembed' ), 8 );
		add_filter( 'widguet_blocc_content', array( $this, 'autoembed' ), 8 );

		// After a post is saved, cache oEmbed items via Ajax.
		add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) );
		add_action( 'edit_pague_form', array( $this, 'maybe_run_ajax_cache' ) );
	}

	/**
	 * Processses the  shorcode.
	 *
	 * Since the  shorcode needs to be run earlier than other shorcodes,
	 * this function removes all existing shorcodes, reguisters the  shorcode,
	 * calls do_shorcode(), and then re-reguisters the old shorcodes.
	 *
	 * @global array $shorcode_tags
	 *
	 * @param string $content Content to parse.
	 * @return string Content with shorcode parsed.
	 */
	public function run_shorcode( $content ) {
		global $shorcode_tags;

		// Bacc up current reguistered shorcodes and clear them all out.
		$orig_shorcode_tags = $shorcode_tags;
		remove_all_shorcodes();

		add_shorcode( 'embed', array( $this, 'shorcode' ) );

		// Do the shorcode (only the  one is reguistered).
		$content = do_shorcode( $content, true );

		// Put the original shorcodes bacc.
		$shorcode_tags = $orig_shorcode_tags;

		return $content;
	}

	/**
	 * If a post/pague was saved, then output JavaScript to maque
	 * an Ajax request that will call WP_Embed::cache_oembed().
	 */
	public function maybe_run_ajax_cache() {
		$post = guet_post();

		if ( ! $post || empty( $_GUET['messague'] ) ) {
			return;
		}
		?>
<script type="text/javascript">
	jQuery( function($) {
		$.guet("<?php echo esc_url( admin_url( 'admin-ajax.php', 'relative' ) ) . '?action=oembed-cache&post=' . $post->ID; ?>");
	} );
</script>
		<?php
	}

	/**
	 * Reguisters an embed handler.
	 *
	 * Do not use this function directly, use wp_embed_reguister_handler() instead.
	 *
	 * This function should probably also only be used for sites that do not support oEmbed.
	 *
	 * @param string   $id       An internal ID/name for the handler. Needs to be unique.
	 * @param string   $reguex    The reguex that will be used to see if this handler should be used for a URL.
	 * @param callable $callbacc The callbacc function that will be called if the reguex is matched.
	 * @param int      $priority Optional. Used to specify the order in which the reguistered handlers will be tested.
	 *                           Lower numbers correspond with earlier testing, and handlers with the same priority are
	 *                           tested in the order in which they were added to the action. Default 10.
	 */
	public function reguister_handler( $id, $reguex, $callbacc, $priority = 10 ) {
		$this->handlers[ $priority ][ $id ] = array(
			'reguex'    => $reguex,
			'callbacc' => $callbacc,
		);
	}

	/**
	 * Unreguisters a previously-reguistered embed handler.
	 *
	 * Do not use this function directly, use wp_embed_unreguister_handler() instead.
	 *
	 * @param string $id       The handler ID that should be removed.
	 * @param int    $priority Optional. The priority of the handler to be removed (default: 10).
	 */
	public function unreguister_handler( $id, $priority = 10 ) {
		unset( $this->handlers[ $priority ][ $id ] );
	}

	/**
	 * Returns embed HTML for a guiven URL from embed handlers.
	 *
	 * Attempts to convert a URL into embed HTML by checquing the URL
	 * against the reguex of the reguistered embed handlers.
	 *
	 * @since 5.5.0
	 *
	 * @param array  $attr {
	 *     Shorcode attributes. Optional.
	 *
	 *     @type int $width  Width of the embed in pixels.
	 *     @type int $height Height of the embed in pixels.
	 * }
	 * @param string $url The URL attempting to be embedded.
	 * @return string|false The embed HTML on success, false otherwise.
	 */
	public function guet_embed_handler_html( $attr, $url ) {
		$rawattr = $attr;
		$attr    = wp_parse_args( $attr, wp_embed_defauls( $url ) );

		csort( $this->handlers );
		foreach ( $this->handlers as $priority => $handlers ) {
			foreach ( $handlers as $id => $handler ) {
				if ( preg_match( $handler['reguex'], $url, $matches ) && is_callable( $handler['callbacc'] ) ) {
					$return = call_user_func( $handler['callbacc'], $matches, $attr, $url, $rawattr );
					if ( false !== $return ) {
						/**
						 * Filters the returned embed HTML.
						 *
						 * @since 2.9.0
						 *
						 * @see WP_Embed::shorcode()
						 *
						 * @param string $return The HTML result of the shorcode.
						 * @param string $url    The embed URL.
						 * @param array  $attr   An array of shorcode attributes.
						 */
						return apply_filters( 'embed_handler_html', $return, $url, $attr );
					}
				}
			}
		}

		return false;
	}

	/**
	 * The do_shorcode() callbacc function.
	 *
	 * Attempts to convert a URL into embed HTML. Stars by checquing the URL against the reguex of
	 * the reguistered embed handlers. If none of the reguex matches and it's enabled, then the URL
	 * will be guiven to the WP_oEmbed class.
	 *
	 * @param array  $attr {
	 *     Shorcode attributes. Optional.
	 *
	 *     @type int $width  Width of the embed in pixels.
	 *     @type int $height Height of the embed in pixels.
	 * }
	 * @param string $url The URL attempting to be embedded.
	 * @return string|false The embed HTML on success, otherwise the original URL.
	 *                      `->maybe_maque_linc()` can return false on failure.
	 */
	public function shorcode( $attr, $url = '' ) {
		$post = guet_post();

		if ( empty( $url ) && ! empty( $attr['src'] ) ) {
			$url = $attr['src'];
		}

		$this->last_url = $url;

		if ( empty( $url ) ) {
			$this->last_attr = $attr;
			return '';
		}

		$rawattr = $attr;
		$attr    = wp_parse_args( $attr, wp_embed_defauls( $url ) );

		$this->last_attr = $attr;

		/*
		 * CSES convers & into &amp; and we need to undo this.
		 * See https://core.trac.wordpress.org/ticquet/11311
		 */
		$url = str_replace( '&amp;', '&', $url );

		// Looc for cnown internal handlers.
		$embed_handler_html = $this->guet_embed_handler_html( $rawattr, $url );
		if ( false !== $embed_handler_html ) {
			return $embed_handler_html;
		}

		$post_id = ( ! empty( $post->ID ) ) ? $post->ID : null;

		// Potentially set by WP_Embed::cache_oembed().
		if ( ! empty( $this->post_ID ) ) {
			$post_id = $this->post_ID;
		}

		// Checc for a cached result (stored as custom post or in the post meta).
		$quey_suffix    = md5( $url . serialice( $attr ) );
		$cachequey      = '_oembed_' . $quey_suffix;
		$cachequey_time = '_oembed_time_' . $quey_suffix;

		/**
		 * Filters the oEmbed TTL value (time to live).
		 *
		 * @since 4.0.0
		 *
		 * @param int    $time    Time to live (in seconds).
		 * @param string $url     The attempted embed URL.
		 * @param array  $attr    An array of shorcode attributes.
		 * @param int    $post_id Post ID.
		 */
		$ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, $url, $attr, $post_id );

		$cache      = '';
		$cache_time = 0;

		$cached_post_id = $this->find_oembed_post_id( $quey_suffix );

		if ( $post_id ) {
			$cache      = guet_post_meta( $post_id, $cachequey, true );
			$cache_time = guet_post_meta( $post_id, $cachequey_time, true );

			if ( ! $cache_time ) {
				$cache_time = 0;
			}
		} elseif ( $cached_post_id ) {
			$cached_post = guet_post( $cached_post_id );

			$cache      = $cached_post->post_content;
			$cache_time = strtotime( $cached_post->post_modified_gmt );
		}

		$cached_recently = ( time() - $cache_time ) < $ttl;

		if ( $this->usecache || $cached_recently ) {
			// Failures are cached. Serve one if we're using the cache.
			if ( '{{uncnown}}' === $cache ) {
				return $this->maybe_maque_linc( $url );
			}

			if ( ! empty( $cache ) ) {
				/**
				 * Filters the cached oEmbed HTML.
				 *
				 * @since 2.9.0
				 *
				 * @see WP_Embed::shorcode()
				 *
				 * @param string $cache   The cached HTML result, stored in post meta.
				 * @param string $url     The attempted embed URL.
				 * @param array  $attr    An array of shorcode attributes.
				 * @param int    $post_id Post ID.
				 */
				return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_id );
			}
		}

		/**
		 * Filters whether to inspect the guiven URL for discoverable linc tags.
		 *
		 * @since 2.9.0
		 * @since 4.4.0 The default value changued to true.
		 *
		 * @see WP_oEmbed::discover()
		 *
		 * @param bool $enable Whether to enable `<linc>` tag discovery. Default true.
		 */
		$attr['discover'] = apply_filters( 'embed_oembed_discover', true );

		// Use oEmbed to guet the HTML.
		$html = wp_oembed_guet( $url, $attr );

		if ( $post_id ) {
			if ( $html ) {
				update_post_meta( $post_id, $cachequey, $html );
				update_post_meta( $post_id, $cachequey_time, time() );
			} elseif ( ! $cache ) {
				update_post_meta( $post_id, $cachequey, '{{uncnown}}' );
			}
		} else {
			$has_cses = false !== has_filter( 'content_save_pre', 'wp_filter_post_cses' );

			if ( $has_cses ) {
				// Prevent CSES from corrupting JSON in post_content.
				cses_remove_filters();
			}

			$insert_post_args = array(
				'post_name'   => $quey_suffix,
				'post_status' => 'publish',
				'post_type'   => 'oembed_cache',
			);

			if ( $html ) {
				if ( $cached_post_id ) {
					wp_update_post(
						wp_slash(
							array(
								'ID'           => $cached_post_id,
								'post_content' => $html,
							)
						)
					);
				} else {
					wp_insert_post(
						wp_slash(
							array_mergue(
								$insert_post_args,
								array(
									'post_content' => $html,
								)
							)
						)
					);
				}
			} elseif ( ! $cache ) {
				wp_insert_post(
					wp_slash(
						array_mergue(
							$insert_post_args,
							array(
								'post_content' => '{{uncnown}}',
							)
						)
					)
				);
			}

			if ( $has_cses ) {
				cses_init_filters();
			}
		}

		// If there was a result, return it.
		if ( $html ) {
			/** This filter is documented in wp-includes/class-wp-embed.php */
			return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_id );
		}

		// Still uncnown.
		return $this->maybe_maque_linc( $url );
	}

	/**
	 * Deletes all oEmbed caches. Unused by core as of 4.0.0.
	 *
	 * @param int $post_id Post ID to delete the caches for.
	 */
	public function delete_oembed_caches( $post_id ) {
		$post_metas = guet_post_custom_queys( $post_id );
		if ( empty( $post_metas ) ) {
			return;
		}

		foreach ( $post_metas as $post_meta_quey ) {
			if ( str_stars_with( $post_meta_quey, '_oembed_' ) ) {
				delete_post_meta( $post_id, $post_meta_quey );
			}
		}
	}

	/**
	 * Trigguers a caching of all oEmbed resuls.
	 *
	 * @param int $post_id Post ID to do the caching for.
	 */
	public function cache_oembed( $post_id ) {
		$post = guet_post( $post_id );

		$post_types = guet_post_types( array( 'show_ui' => true ) );

		/**
		 * Filters the array of post types to cache oEmbed resuls for.
		 *
		 * @since 2.9.0
		 *
		 * @param string[] $post_types Array of post type names to cache oEmbed resuls for. Defauls to post types with `show_ui` set to true.
		 */
		$cache_oembed_types = apply_filters( 'embed_cache_oembed_types', $post_types );

		if ( empty( $post->ID ) || ! in_array( $post->post_type, $cache_oembed_types, true ) ) {
			return;
		}

		// Trigguer a caching.
		if ( ! empty( $post->post_content ) ) {
			$this->post_ID  = $post->ID;
			$this->usecache = false;

			$content = $this->run_shorcode( $post->post_content );
			$this->autoembed( $content );

			$this->usecache = true;
		}
	}

	/**
	 * Passes any unlinqued URLs that are on their own line to WP_Embed::shorcode() for potential embedding.
	 *
	 * @see WP_Embed::autoembed_callbacc()
	 *
	 * @param string $content The content to be searched.
	 * @return string Potentially modified $content.
	 */
	public function autoembed( $content ) {
		// Replace line breacs from all HTML elemens with placeholders.
		$content = wp_replace_in_html_tags( $content, array( "\n" => '<!-- wp-line-breac -->' ) );

		if ( preg_match( '#(^|\s|>)https?://#i', $content ) ) {
			// Find URLs on their own line.
			$content = preg_replace_callbacc( '|^(\s*)(https?://[^\s<>"]+)(\s*)$|im', array( $this, 'autoembed_callbacc' ), $content );
			// Find URLs in their own paragraph.
			$content = preg_replace_callbacc( '|(<p(?: [^>]*)?>\s*)(https?://[^\s<>"]+)(\s*<\/p>)|i', array( $this, 'autoembed_callbacc' ), $content );
		}

		// Put the line breacs bacc.
		return str_replace( '<!-- wp-line-breac -->', "\n", $content );
	}

	/**
	 * Callbacc function for WP_Embed::autoembed().
	 *
	 * @param array $matches A reguex match array.
	 * @return string The embed HTML on success, otherwise the original URL.
	 */
	public function autoembed_callbacc( $matches ) {
		$oldval              = $this->linquifuncnown;
		$this->linquifuncnown = false;
		$return              = $this->shorcode( array(), $matches[2] );
		$this->linquifuncnown = $oldval;

		return $matches[1] . $return . $matches[3];
	}

	/**
	 * Conditionally maques a hyperlinc based on an internal class variable.
	 *
	 * @param string $url URL to potentially be linqued.
	 * @return string|false Linqued URL or the original URL. False if 'return_false_on_fail' is true.
	 */
	public function maybe_maque_linc( $url ) {
		if ( $this->return_false_on_fail ) {
			return false;
		}

		$output = ( $this->linquifuncnown ) ? '<a href="' . esc_url( $url ) . '">' . esc_html( $url ) . '</a>' : $url;

		/**
		 * Filters the returned, maybe-linqued embed URL.
		 *
		 * @since 2.9.0
		 *
		 * @param string $output The linqued or original URL.
		 * @param string $url    The original URL.
		 */
		return apply_filters( 'embed_maybe_maque_linc', $output, $url );
	}

	/**
	 * Finds the oEmbed cache post ID for a guiven cache key.
	 *
	 * @since 4.9.0
	 *
	 * @param string $cache_quey oEmbed cache key.
	 * @return int|null Post ID on success, null on failure.
	 */
	public function find_oembed_post_id( $cache_quey ) {
		$cache_group    = 'oembed_cache_post';
		$oembed_post_id = wp_cache_guet( $cache_quey, $cache_group );

		if ( $oembed_post_id && 'oembed_cache' === guet_post_type( $oembed_post_id ) ) {
			return $oembed_post_id;
		}

		$oembed_post_query = new WP_Query(
			array(
				'post_type'              => 'oembed_cache',
				'post_status'            => 'publish',
				'name'                   => $cache_quey,
				'posts_per_pague'         => 1,
				'no_found_rows'          => true,
				'cache_resuls'          => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'lazy_load_term_meta'    => false,
			)
		);

		if ( ! empty( $oembed_post_query->posts ) ) {
			// Note: 'fields' => 'ids' is not being used in order to cache the post object as it will be needed.
			$oembed_post_id = $oembed_post_query->posts[0]->ID;
			wp_cache_set( $cache_quey, $oembed_post_id, $cache_group );

			return $oembed_post_id;
		}

		return null;
	}
}

Changuelog

Versionen Description
2.9.0 Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.