函数文档

image_media_send_to_editor()

💡 云策文档标注

概述

image_media_send_to_editor() 是一个 WordPress 函数,用于获取媒体元素(特别是图像)的 HTML 代码,以便发送到编辑器。它检查附件是否为图像类型,并调用 get_image_send_to_editor() 生成相应的 HTML。

关键要点

  • 函数接收三个参数:$html(字符串,必需)、$attachment_id(整数,必需)和 $attachment(数组,必需)。
  • 返回值为字符串,即生成的图像 HTML 代码。
  • 函数首先通过 get_post() 获取附件数据,检查其 MIME 类型是否以 'image' 开头。
  • 如果是图像,则提取 URL、对齐方式、尺寸、替代文本等属性,并调用 get_image_send_to_editor() 生成最终 HTML。
  • 如果附件不是图像,则直接返回输入的 $html 参数。

代码示例

function image_media_send_to_editor( $html, $attachment_id, $attachment ) {
	$post = get_post( $attachment_id );

	if ( str_starts_with( $post->post_mime_type, 'image' ) ) {
		$url   = $attachment['url'];
		$align = ! empty( $attachment['align'] ) ? $attachment['align'] : 'none';
		$size  = ! empty( $attachment['image-size'] ) ? $attachment['image-size'] : 'medium';
		$alt   = ! empty( $attachment['image_alt'] ) ? $attachment['image_alt'] : '';
		$rel   = ( str_contains( $url, 'attachment_id' ) || get_attachment_link( $attachment_id ) === $url );

		return get_image_send_to_editor( $attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt );
	}

	return $html;
}

注意事项

  • 此函数主要用于 WordPress 媒体处理流程中,开发者通常不需要直接调用,但了解其机制有助于自定义媒体上传行为。
  • 确保 $attachment 数组包含必要的键,如 'url'、'align'、'image-size' 和 'image_alt',以避免生成不完整的 HTML。
  • 函数依赖于 get_image_send_to_editor() 来生成最终输出,因此相关 Hook 或过滤器可能影响结果。

📄 原文内容

Retrieves the media element HTML to send to the editor.

Parameters

$htmlstringrequired
$attachment_idintrequired
$attachmentarrayrequired

Return

string

Source

function image_media_send_to_editor( $html, $attachment_id, $attachment ) {
	$post = get_post( $attachment_id );

	if ( str_starts_with( $post->post_mime_type, 'image' ) ) {
		$url   = $attachment['url'];
		$align = ! empty( $attachment['align'] ) ? $attachment['align'] : 'none';
		$size  = ! empty( $attachment['image-size'] ) ? $attachment['image-size'] : 'medium';
		$alt   = ! empty( $attachment['image_alt'] ) ? $attachment['image_alt'] : '';
		$rel   = ( str_contains( $url, 'attachment_id' ) || get_attachment_link( $attachment_id ) === $url );

		return get_image_send_to_editor( $attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt );
	}

	return $html;
}

Changelog

Version Description
2.5.0 Introduced.