函数文档

_wp_preview_post_thumbnail_filter()

💡 云策文档标注

概述

_wp_preview_post_thumbnail_filter() 是一个 WordPress 过滤器函数,用于在预览模式下设置文章缩略图。它通过过滤元数据查找来确保预览时显示正确的缩略图。

关键要点

  • 这是一个过滤器函数,用于处理文章缩略图的元数据查找。
  • 仅在预览模式下生效,检查 $_REQUEST 参数和文章类型。
  • 返回默认值或缩略图元数据数组。

代码示例

function _wp_preview_post_thumbnail_filter( $value, $post_id, $meta_key ) {
    $post = get_post();

    if ( ! $post ) {
        return $value;
    }

    if ( empty( $_REQUEST['_thumbnail_id'] ) || empty( $_REQUEST['preview_id'] )
        || $post->ID !== $post_id || $post_id !== (int) $_REQUEST['preview_id']
        || '_thumbnail_id' !== $meta_key || 'revision' === $post->post_type
    ) {
        return $value;
    }

    $thumbnail_id = (int) $_REQUEST['_thumbnail_id'];

    if ( $thumbnail_id ) {
        return array( $thumbnail_id );
    }

    return $value;
}

注意事项

  • 函数仅在预览模式下有效,依赖于 $_REQUEST['_thumbnail_id'] 和 $_REQUEST['preview_id'] 参数。
  • 如果条件不满足,将返回原始值,确保不影响正常操作。
  • 自 WordPress 4.6.0 版本引入。

📄 原文内容

Filters post thumbnail lookup to set the post thumbnail.

Parameters

$valuenull|array|stringrequired
The value to return – a single metadata value, or an array of values.
$post_idintrequired
Post ID.
$meta_keystringrequired
Meta key.

Return

null|array The default return value or the post thumbnail meta array.

Source

function _wp_preview_post_thumbnail_filter( $value, $post_id, $meta_key ) {
	$post = get_post();

	if ( ! $post ) {
		return $value;
	}

	if ( empty( $_REQUEST['_thumbnail_id'] ) || empty( $_REQUEST['preview_id'] )
		|| $post->ID !== $post_id || $post_id !== (int) $_REQUEST['preview_id']
		|| '_thumbnail_id' !== $meta_key || 'revision' === $post->post_type
	) {
		return $value;
	}

	$thumbnail_id = (int) $_REQUEST['_thumbnail_id'];

	if ( $thumbnail_id <= 0 ) {
		return '';
	}

	return (string) $thumbnail_id;
}

Changelog

Version Description
4.6.0 Introduced.