get_post_embed_html()WP 4.4.0

Получает готовый HTML код oEmbed встраивания указанной записи. Предполагается использовать этот код для встраивания записи на другом ресурсе.

Что такое Embed читайте здесь: oEmbed в WordPress.

Работает на основе: get_post_embed_url()
Хуки из функции

Возвращает

Строку|false. HTML код: Embed код. Вернет false, если указанной записи не существует.

Использование

get_post_embed_html( $width, $height, $post );
$width(число) (обязательный)
Ширина встраивания. Указывается для iframe.
$height(число) (обязательный)
Высота встраивания. Указывается для iframe.
$post(число/WP_Post)
ID или объект записи, код встраивания которой нужно получить.
По умолчанию: null (текущая запись в цикле)

Примеры

0

#1 Пример получения oEmbed HTML кода

echo get_post_embed_html( 400, 250, 1 );

В результате получим:

<blockquote class="wp-embedded-content"><a href="/handbook/codex/hooks">Как работают хуки в WordPress (фильтры и события)</a></blockquote>
<script type='text/javascript'>
<!--//--><![CDATA[//><!--
		!function(a,b){"use strict";function c(){if(!e){e=!0;var a,c,d,f,g=-1!==navigator.appVersion.indexOf("MSIE 10"),h=!!navigator.userAgent.match(/Trident.*rv:11\./),i=b.querySelectorAll("iframe.wp-embedded-content"),j=b.querySelectorAll("blockquote.wp-embedded-content");for(c=0;c<j.length;c++)j[c].style.display="none";for(c=0;c<i.length;c++)if(d=i[c],d.style.display="",!d.getAttribute("data-secret")){if(f=Math.random().toString(36).substr(2,10),d.src+="#?secret="+f,d.setAttribute("data-secret",f),g||h)a=d.cloneNode(!0),a.removeAttribute("security"),d.parentNode.replaceChild(a,d)}else;}}var d=!1,e=!1;if(b.querySelector)if(a.addEventListener)d=!0;if(a.wp=a.wp||{},!a.wp.receiveEmbedMessage)if(a.wp.receiveEmbedMessage=function(c){var d=c.data;if(d.secret||d.message||d.value)if(!/[^a-zA-Z0-9]/.test(d.secret)){var e,f,g,h,i,j=b.querySelectorAll('iframe[data-secret="'+d.secret+'"]'),k=b.querySelectorAll('blockquote[data-secret="'+d.secret+'"]');for(e=0;e<k.length;e++)k[e].style.display="none";for(e=0;e<j.length;e++)if(f=j[e],c.source===f.contentWindow){if(f.style.display="","height"===d.message){if(g=parseInt(d.value,10),g>1e3)g=1e3;else if(200>~~g)g=200;f.height=g}if("link"===d.message)if(h=b.createElement("a"),i=b.createElement("a"),h.href=f.getAttribute("src"),i.href=d.value,i.host===h.host)if(b.activeElement===f)a.top.location.href=d.value}else;}},d)a.addEventListener("message",a.wp.receiveEmbedMessage,!1),b.addEventListener("DOMContentLoaded",c,!1),a.addEventListener("load",c,!1)}(window,document);
//--><!]]>
</script><iframe sandbox="allow-scripts" security="restricted" src="/handbook/codex/hooks/embed" width="400" height="300" title="Вставленная запись WordPress" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" class="wp-embedded-content"></iframe>

А вот так это будет выглядеть на странице:

Как работают хуки в WordPress (фильтры и события)

Список изменений

С версии 4.4.0 Введена.

Код get_post_embed_html() WP 6.5.2

function get_post_embed_html( $width, $height, $post = null ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$embed_url = get_post_embed_url( $post );

	$secret     = wp_generate_password( 10, false );
	$embed_url .= "#?secret={$secret}";

	$output = sprintf(
		'<blockquote class="wp-embedded-content" data-secret="%1$s"><a href="%2$s">%3$s</a></blockquote>',
		esc_attr( $secret ),
		esc_url( get_permalink( $post ) ),
		get_the_title( $post )
	);

	$output .= sprintf(
		'<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>',
		esc_url( $embed_url ),
		absint( $width ),
		absint( $height ),
		esc_attr(
			sprintf(
				/* translators: 1: Post title, 2: Site title. */
				__( '&#8220;%1$s&#8221; &#8212; %2$s' ),
				get_the_title( $post ),
				get_bloginfo( 'name' )
			)
		),
		esc_attr( $secret )
	);

	/*
	 * Note that the script must be placed after the <blockquote> and <iframe> due to a regexp parsing issue in
	 * `wp_filter_oembed_result()`. Because of the regex pattern starts with `|(<blockquote>.*?</blockquote>)?.*|`
	 * wherein the <blockquote> is marked as being optional, if it is not at the beginning of the string then the group
	 * will fail to match and everything will be matched by `.*` and not included in the group. This regex issue goes
	 * back to WordPress 4.4, so in order to not break older installs this script must come at the end.
	 */
	$output .= wp_get_inline_script_tag(
		file_get_contents( ABSPATH . WPINC . '/js/wp-embed' . wp_scripts_get_suffix() . '.js' )
	);

	/**
	 * Filters the embed HTML output for a given post.
	 *
	 * @since 4.4.0
	 *
	 * @param string  $output The default iframe tag to display embedded content.
	 * @param WP_Post $post   Current post object.
	 * @param int     $width  Width of the response.
	 * @param int     $height Height of the response.
	 */
	return apply_filters( 'embed_html', $output, $post, $width, $height );
}