简体   繁体   English

WordPress如果声明功能图像

[英]WordPress If statement Feature Image

What I am trying to achieve is for posts that haven't set a featured image to use the default CSS background-image . 我想要实现的是没有设置特色图像的帖子使用默认的CSS背景图像。 That means every post will have an image. 这意味着每个帖子都会有一张图片。

<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'thumbnail') ); ?>
 <div class="entry-header featureImg" style="background-image: url('<?php echo $url ?>')"></div>

Basically here is the thing : 基本上就是这样的事情:

<div class="entry-header featureImg" style="background-image: url('<?php echo $url ?>')">

for post without featured image set the 'background-image' should be the default one from CSS because as the code is actually written the bg image for those posts(whitout feat image set) is : 对于没有特色图像集的帖子,'background-image'应该是CSS中的默认值,因为代码实际上是为这些帖子写的bg图像(whitout feat图像集)是:

background-image: url(''); //taken from page source

this should be done with php if statements but I have no idea how to work with this syntax : 这应该用php if语句完成,但我不知道如何使用这种语法:

`<?php if($has_post_thumbnail) : ?>

  <?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID,'thumbnail') ); ?>
<div class="entry-header featureImg" style="background-image: url('<?php echo $url ?>')">

<?php else : ?>

    <div class="entry-header featureImg">

<?php endif; ?>
?>`

In this case you just need to use the if statement on whether or not to show the whole style tag or not. 在这种情况下,您只需要使用if语句来判断是否显示整个样式标记。 It's cleaner to add these sort of things to your functions.php file though so if you add this there: 将这些东西添加到你的functions.php文件中更加清晰,如果你在那里添加它:

function alternative_bg_img() {
  global $post;
  if (has_post_thumbnail()) {
    var $image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID, 'thumbnail ') );
    echo 'style="background-image:url(' + $image + ');';
  }
}

And then add: 然后添加:

<div class="entry-header featureImg" <?php alternative_bg_img(); ?>>

Then the whole style tag (not just the image) will only appear if you there is a featured image. 然后,只有当您有特色图像时,才会显示整个style标记(不仅仅是图像)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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