簡體   English   中英

使用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標簽的圖像。 你想要做的是獲取圖像URL

$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); $url = $thumb['0'];

if ( has_post_thumbnail() ) {echo $url;}

我喜歡使用background-size:覆蓋它的全寬。 如果它不只是刪除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">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM