The post_thumbnail_url WordPress PHP filter allows you to modify the URL of a post thumbnail image.
Usage
add_filter('post_thumbnail_url', 'your_custom_function', 10, 3); function your_custom_function($thumbnail_url, $post, $size) { // your custom code here return $thumbnail_url; }
Parameters
$thumbnail_url
(string|false): Post thumbnail URL or false if the post does not exist.$post
(int|WP_Post|null): Post ID or WP_Post object. Default is global$post
.$size
(string|int[]): Registered image size to retrieve the source for or a flat array of height and width dimensions. Default ‘post-thumbnail’.
More information
See WordPress Developer Resources: post_thumbnail_url
Examples
Change the thumbnail URL for specific post ID
This example modifies the thumbnail URL for a specific post with the ID 123
.
add_filter('post_thumbnail_url', 'change_thumbnail_url_for_post', 10, 3); function change_thumbnail_url_for_post($thumbnail_url, $post, $size) { if ($post->ID == 123) { $thumbnail_url = 'https://example.com/custom-image.jpg'; } return $thumbnail_url; }
Add a query string to the thumbnail URL
This example adds a query string to the thumbnail URL to prevent caching.
add_filter('post_thumbnail_url', 'prevent_cache_thumbnail_url', 10, 3); function prevent_cache_thumbnail_url($thumbnail_url, $post, $size) { $thumbnail_url = add_query_arg('timestamp', time(), $thumbnail_url); return $thumbnail_url; }
Replace the thumbnail URL domain
This example replaces the domain of the thumbnail URL with a CDN domain.
add_filter('post_thumbnail_url', 'replace_thumbnail_url_domain', 10, 3); function replace_thumbnail_url_domain($thumbnail_url, $post, $size) { $thumbnail_url = str_replace('https://yourwebsite.com', 'https://yourcdn.com', $thumbnail_url); return $thumbnail_url; }
Use a placeholder image if thumbnail is missing
This example uses a placeholder image if the post thumbnail is not available.
add_filter('post_thumbnail_url', 'use_placeholder_if_thumbnail_missing', 10, 3); function use_placeholder_if_thumbnail_missing($thumbnail_url, $post, $size) { if (!$thumbnail_url) { $thumbnail_url = 'https://example.com/placeholder-image.jpg'; } return $thumbnail_url; }
Change the thumbnail size for specific category
This example changes the thumbnail size for posts in the ‘featured’ category.
add_filter('post_thumbnail_url', 'change_thumbnail_size_for_featured_category', 10, 3); function change_thumbnail_size_for_featured_category($thumbnail_url, $post, $size) { if (has_category('featured', $post)) { $size = 'large'; $thumbnail_url = wp_get_attachment_image_url(get_post_thumbnail_id($post), $size); } return $thumbnail_url; }