Possible to swap in a placeholder image globally for the_post_thumbnail_url if one doesn’t exist?

I am working on a new theme for a site, but the majority of the posts don’t have a featured image set. Throughout the new theme I am pulling in featured images using the_post_thumbnail_url. I am wondering if there is a function I can add to functions.php to override this url, globally, with a url to a placeholder image if there is no featured image assigned to the post.

2 Answers
2

If you know the URL of the placeholder image, you sure can do it.

get_the_post_thumbnail_url() function calls the wp_get_attachment_image_url() function which in turns calls the
wp_get_attachment_image_src() function to get the source of the post thumbnail. wp_get_attachment_url() returns the result from wp_get_attachment_image_src filter. So we can use that filter to modify the result if there is no image and the size is ‘post-thumbnail’.

namespace StackExchange\WordPress;

function image_src( $image, $attachment_id, $size, $icon ) {
  $default = [
    'https://example.com/img.gif',
  ];
  return ( false === $image && 'post-thumbnail' === $size ) ? $default : $image;
}
\add_filter( 'wp_get_attachment_image_src', __NAMESPACE__ . '\image_src', 10, 4 );

Leave a Comment