我可以看到两种不同的方法来实现这一点。
解决方案 1(来自媒体库的文件)
有一个过滤器可用于覆盖(或提供默认值)get_the_post_thumbnail_url() 函数。
在此过程中,函数将调用get_post_meta(),最终将调用过滤器get_{$meta_type}_metadata。
你可以做的是用类似这样的东西来挂钩这个过滤器:
add_filter( 'get_post_metadata', function ( $metadata, int $object_id, string $meta_key, bool $single, string $meta_type ) {
// @todo fetch a predefined file ID (this must be an existing file from the media library).
return $metadata;
}, 10, );
此方法的缺点是您无法提供一些随机 URL,但您需要使用媒体库中的现有文件。
解决方案 2(任何自定义 URL)
为了为您的帖子缩略图提供完全可定制的 URL,您需要挂钩 3 个不同的函数。
add_filter( 'has_post_thumbnail', 'so52332168_hasPostThumbnail', 10, 3 );
add_filter( 'get_post_metadata', 'so52332168_getPostThumbnailFileId', 10, 4 );
add_filter( 'wp_get_attachment_image_src', 'so52332168_getPostThumbnailSrc', 10, 4 );
/**
* Use any way you want to determine if your post should have a custom thumbnail URL.
*
* @param $has_thumbnail
* @param $post_id
* @param $thumbnail_id
*
* @return bool
*/
function so52332168_hasPostThumbnail( $has_thumbnail, $post_id, $thumbnail_id ) {
if ( ! $has_thumbnail ) {
// @todo check if the $post_id match any rule to get a custom thumbnail.
// if so, return true here
return true;
}
return $has_thumbnail;
}
/**
* Force override the thumbnail URL.
*
* @param $value
* @param $object_id
* @param $meta_key
* @param $single
*
* @return int
*/
function so52332168_getPostThumbnailFileId( $value, $object_id, $meta_key, $single ) {
if ( '_thumbnail_id' === $meta_key ) {
// @todo check if the current $object_id should get a custom thumbnail (probably the same check as above)
global $customPostThumbnailUrl;
$customPostThumbnailUrl = 'https://placekitten.com/300/300';
// return the fake thumbnail id -> this should absolutely never match an actual file id
return PHP_INT_MAX;
}
}
}
return $value;
}
/**
* Eventually return the URL that we "calculate" for the post.
*
* @param $image
* @param $attachment_id
* @param $size
* @param $icon
*
* @return array
*/
function so52332168_getPostThumbnailSrc( $image, $attachment_id, $size, $icon ) {
global $customPostThumbnailUrl;
// check that the attachment id is the one we returned previously
if ( (PHP_INT_MAX === $attachment_id) && $customPostThumbnailUrl ) {
// return our custom image URL
return [ $customPostThumbnailUrl ];
}
return $image;
}