Opened 4 years ago
Last modified 2 years ago
#40547 reviewing enhancement
Add a filter to get_the_post_thumbnail_url
Reported by: |
|
Owned by: |
|
---|---|---|---|
Milestone: | Future Release | Priority: | normal |
Severity: | normal | Version: | 4.8 |
Component: | Post Thumbnails | Keywords: | |
Focuses: | Cc: |
Description
Since we have a filter for the function get_the_post_thumbnail:
return apply_filters( 'post_thumbnail_html', $html, $post->ID, $post_thumbnail_id, $size, $attr )
should we also have a filter to the function get_the_post_thumbnail_url?
I have a situation where I have made a plugin that allows setting a post_thumbnail image as an external url or similar so I am using the mentioned filter for displaying a custom post thumbnail.
If a theme uses the function get_the_post_thumbnail_url, there is no way to return the custom url for the post thumbnail.
Something like this could be helpful then:
function get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' ) {
$post_thumbnail_id = get_post_thumbnail_id( $post );
if ( ! $post_thumbnail_id ) {
return false;
}
return apply_filters( 'get_the_post_thumbnail_url', wp_get_attachment_image_url( $post_thumbnail_id, $size ), $post->ID );
}
Attachments (1)
Change History (7)
#1
@
4 years ago
Hi @ibenic, welcome to WordPress Trac! Thanks for the ticket.
Related: #23983 (suggests a filter for get_post_thumbnail_id()
).
If a theme uses the function get_the_post_thumbnail_url, there is no way to return the custom url for the post thumbnail.
This should be possible using get_post_metadata
and wp_get_attachment_image_src
as a workaround:
function wp40547_filter_post_thumbnail_id( $null, $post_id, $meta_key, $single ) { if ( '_thumbnail_id' !== $meta_key ) { return $null; } // Set a non-empty $attachment_id for the passed $post_id. Doesn't have to be an existing // attachment, just a value you would check later in wp40547_filter_post_thumbnail_src(). // $attachment_id = ... return $attachment_id; } add_filter( 'get_post_metadata', 'wp40547_filter_post_thumbnail_id', 10, 4 ); function wp40547_filter_post_thumbnail_src( $image, $attachment_id, $size, $icon ) { if ( 'post-thumbnail' !== $size ) { return $image; } // Set the image URL for the passed $attachment_id. // $image[0] = ... return $image; } add_filter( 'wp_get_attachment_image_src', 'wp40547_filter_post_thumbnail_src', 10, 4 );
#2
@
4 years ago
Hi @SergeyBiryukov, thank you for this suggestion.
It did not occur to me to hook into metadata for making such modifications. I'll see to implement this approach and check if it all works well or breaks other functions which require the thumbnail_id.
#3
@
4 years ago
@SergeyBiryukov Since the get_{$meta_type}_metadata filter happens before wp_cache_get() in get_metadata you can't actually filter the data that exists, only return an alterative. Personally if I had a choice I'd opt for the filter in #23983, but why not both?
40547 - Patch with filter