Search code examples
wordpressimageif-statementstatementswordpress-featured-image

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 . 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: 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($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; ?>
?>`

Solution

  • In this case you just need to use the if statement on whether or not to show the whole style tag or not. It's cleaner to add these sort of things to your functions.php file though so if you add this there:

    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.