使用 PHP 逻辑的内联 HTML 背景图像


Inline HTML background-image using PHP logic?

是否可以使用我的PHP逻辑将WordPress帖子的特色图像显示为div的内联背景图像?这是我的尝试:

                <div class="rounding-image" style="background-image: url(
                    <?php
                        if ( $thumbnail == true ) {
                            // If the post has a feature image, show it
                            if ( has_post_thumbnail() ) {
                                the_post_thumbnail( $thumbsize );
                            // Else if the post has a mime type that starts with "image/" then show the image directly.
                            } elseif ( 'image/' == substr( $post->post_mime_type, 0, 6 ) ) {
                                echo wp_get_attachment_image( $post->ID, $thumbsize );
                            }
                        }
                    ?>
                )"></div>

这不是抛出特定的错误,而是显示图像所在的位置)">

>the_post_thumbnail显示带有 img 标记的图像。您要做的是获取图像网址

$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); $url = $thumb['0'];
if ( has_post_thumbnail() ) {echo $url;}

我喜欢使用背景大小:如果它的全宽,则覆盖。 如果不仅仅是删除CSS的那部分

<?php if (has_post_thumbnail( $page->ID ) ) { ?>
      <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $page->ID ), 'single-post-thumbnail' ); ?>
<header style="background:url(<?php echo $image[0]; ?>) 50%  50% no-repeat;background-size: cover;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cover;"></header>
<?php } ?>

使用它,它会将背景图像设置为特色图像(如果存在)。这允许您在未设置特色图像的情况下通过 CSS 设置默认值。

<?php 
    global $post; 
    $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' ); 
    if ( has_post_thumbnail() ) :
?>
    <div class="rounding-image" style="background: url(<?php echo $src[0]; ?> ) !important;">
<?php else : ?>
    <div id="rounding-image">