如果 php 中没有图像,如何设置默认图像

Gok*_*P P 0 html php wordpress

我有一个显示图像的代码,但如果没有可用的图像需要显示默认图像

目前,我有这个代码

<?php ?>
<img src="<?php echo get_the_post_thumbnail_url($post->ID); ?>"/>  
<?php ?> 
Run Code Online (Sandbox Code Playgroud)

Pra*_*lan 5

使用has_post_thumbnail()方法检查帖子是否有缩略图,并根据缩略图提供默认图像。

\n\n
<?php if (has_post_thumbnail()) : ?>\n<img src="<?php echo get_the_post_thumbnail_url($post->ID); ?>"/>\xe2\x80\x82\xe2\x80\x82\n<?php else: ?>\n\xe2\x80\x82\xe2\x80\x82 <!-- default image here -->\n<?php endif; ?>\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

您可以使用三元运算符来减少代码。

\n\n
<img src="<?php echo (has_post_thumbnail() ? get_the_post_thumbnail_url($post->ID) : \'default_image.jpg\'); ?>"/>\xe2\x80\x82\xe2\x80\x82\n
Run Code Online (Sandbox Code Playgroud)\n