【问题标题】:Inline HTML background-image using PHP logic?使用 PHP 逻辑的内联 HTML 背景图像?
【发布时间】:2015-04-01 23:28:48
【问题描述】:

是否可以使用我的 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>

这不会引发特定错误,而是在图像所在的位置显示)"&gt;

【问题讨论】:

  • 我猜 $thumbnail == false 在这里。你没有其他人可以处理这个案子。尝试简单地添加 else where $thumbnail == false 并回显一些东西,任何东西。如果这确实回显,您就知道如何处理它了。

标签: php html wordpress logic background-image


【解决方案1】:

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;}

【讨论】:

    【解决方案2】:

    我喜欢使用 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 } ?>
    

    【讨论】:

      【解决方案3】:

      使用这个,它会将背景图像设置为特色图像(如果存在)。这允许您通过 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">
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-09
        • 1970-01-01
        • 2016-10-20
        • 2021-01-25
        • 2018-01-30
        • 1970-01-01
        • 2013-01-10
        • 1970-01-01
        相关资源
        最近更新 更多