简体   繁体   English

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

[英]Inline HTML background-image using PHP logic?

Is it possible to use my PHP logic used to display a WordPress post's featured image as the inline background image of a div? 是否可以使用我的PHP逻辑用于显示WordPress帖子的特色图像作为div的内嵌背景图像? Here is my attempt: 这是我的尝试:

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

This isn't throwing a specific error, but rather displaying )"> where the image would be. 这不会引发特定错误,而是显示)">图像所在的位置。

the_post_thumbnail displays the image with the img tag. the_post_thumbnail显示带有img标签的图像。 What you want to do is get the image URL 你想要做的是获取图像URL

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

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

I like to use background-size: cover if its full width. 我喜欢使用background-size:覆盖它的全宽。 if it's not just remove that part of the css 如果它不只是删除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 } ?>

Use this, it will set the background image to the featured image if one exists. 使用此选项,它会将背景图像设置为特色图像(如果存在)。 This allows you to set a default via CSS in case a featured image is not set. 这允许您在未设置特色图像的情况下通过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