函数文档

wp_get_attachment_caption()

💡 云策文档标注

概述

wp_get_attachment_caption() 函数用于获取附件的标题。它接受一个可选的附件 ID 参数,返回标题字符串或失败时返回 false。

关键要点

  • 函数参数:$post_id(可选,整数类型,默认为全局 $post 的 ID)
  • 返回值:成功时返回附件标题字符串,失败时返回 false
  • 函数会检查附件是否存在且 post_type 为 'attachment',否则返回 false
  • 通过 apply_filters('wp_get_attachment_caption', $caption, $post->ID) 钩子允许过滤标题

代码示例

function wp_get_attachment_caption( $post_id = 0 ) {
	$post_id = (int) $post_id;
	$post    = get_post( $post_id );

	if ( ! $post ) {
		return false;
	}

	if ( 'attachment' !== $post->post_type ) {
		return false;
	}

	$caption = $post->post_excerpt;

	/**
	 * Filters the attachment caption.
	 *
	 * @since 4.6.0
	 *
	 * @param string $caption Caption for the given attachment.
	 * @param int    $post_id Attachment ID.
	 */
	return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
}

注意事项

  • 函数在 WordPress 4.6.0 版本中引入
  • 相关函数包括 get_post() 和 get_the_post_thumbnail_caption()
  • 使用 apply_filters() 钩子可以自定义标题输出

📄 原文内容

Retrieves the caption for an attachment.

Parameters

$post_idintoptional
Attachment ID. Default is the ID of the global $post.

Return

string|false Attachment caption on success, false on failure.

Source

function wp_get_attachment_caption( $post_id = 0 ) {
	$post_id = (int) $post_id;
	$post    = get_post( $post_id );

	if ( ! $post ) {
		return false;
	}

	if ( 'attachment' !== $post->post_type ) {
		return false;
	}

	$caption = $post->post_excerpt;

	/**
	 * Filters the attachment caption.
	 *
	 * @since 4.6.0
	 *
	 * @param string $caption Caption for the given attachment.
	 * @param int    $post_id Attachment ID.
	 */
	return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
}

Hooks

apply_filters( ‘wp_get_attachment_caption’, string $caption, int $post_id )

Filters the attachment caption.

Changelog

Version Description
4.6.0 Introduced.