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.
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.
- Related: wordpress.stackexchange/questions/157170/… – WebElaine Commented Apr 4, 2018 at 21:45
2 Answers
Reset to default 5If 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/img.gif',
];
return ( false === $image && 'post-thumbnail' === $size ) ? $default : $image;
}
\add_filter( 'wp_get_attachment_image_src', __NAMESPACE__ . '\image_src', 10, 4 );
Well, depending on the thumbnails you have defined, you could do a check if the post "has" a thumbnail, display it; but if it doesn't, you can show a default image stored somewhere in your theme's image directory, like so:
// Other code to fetch the post
if ( has_post_thumbnail() ) {
the_post_thumbnail('slide');
}
else {
<img src="<?php echo get_template_directory_uri() ?>/images/default-image.jpg" class="attachment-slide wp-post-image">
}
This is assuming you have already added the thumbnail slide
like so:
add_image_size( 'slide', 500, 400, true ); // width=500, height=400
Hope this helps.