最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

post thumbnails - Possible to swap in a placeholder image globally for the_post_thumbnail_url if one doesn't exist?

programmeradmin3浏览0评论

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.

Share Improve this question asked Apr 4, 2018 at 21:29 APAD1APAD1 4053 gold badges6 silver badges20 bronze badges 1
  • Related: wordpress.stackexchange/questions/157170/… – WebElaine Commented Apr 4, 2018 at 21:45
Add a comment  | 

2 Answers 2

Reset to default 5

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/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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论