简体   繁体   中英

Display default image as div background, when there is no post thumbnail in WordPress

I have the following expression, to get the post thumbnail, and if the post has no thumbnail, it should set a default image as the <div> background.

<?php $backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');if(empty($backgroundImg)) $backgroundImg = APP_URL . "images/common/no-image.png";?>

<div class="ach_img" style="background: url('<?php echo $backgroundImg[0]; ?>') no-repeat;"></div>

The problem is that it's returning style="background: url('h') no-repeat; . I guess the problem is in <?php echo $backgroundImg[0]; ?> , but I can't figure out how to correct it.

Based on the following information of the official code reference:

returns an array (url, width, height, is_intermediate), or false, if no image is available.
source: https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

You can try the following solution:

<?php
$att_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');

if ($att_image === false) {
    $imgPath = APP_URL.'images/common/no-image.png';
} else {
    $imgPath = $att_image[0];
}
?>

<div class="ach_img" style="background: url('<?= $imgPath ?>') no-repeat;"></div>

$backgroundImg[0] will return only the first character of APP_URL if no featured image. Try this instead.

<?php
$backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full'); $bgimg=$backgroundImg[0];
if(empty($backgroundImg)) $bgimg = APP_URL . "images/common/no-image.png";
?>
<div class="ach_img" style="background: url('<?php echo $bgimg; ?>') no-repeat;"></div>
$post_id = get_the_ID(); // Get current page ID
$feat_image =  wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'full' ); // To get source path of featured image.
$image_url = $feat_image[0]; // This will return thumbnail image path

Now check admin user has selected featured image or not. If it is empty, it means not selected.

if(empty($image)){
     $bgimg_path = "Your Image Path";
     echo '<div class="bgimage-section" style="background: url('<?php echo $bgimg_path; ?>') no-repeat;"></div>';
}

Hope this code will help you.

您可以使用var_dump($backgroundImg)查看返回的结果,然后从那里进行编辑。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM