• Resolved hrrubin

    (@hrrubin)


    I have a website with the code

    <?php
    $image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
    <div id="featuredimage" style="background-image: url('<?php echo $image; ?>')">
    <?php ?>
    </div>

    which give every page and post featured image space, even if they don’t have one. How do I make sure this div will only show when the post/page have an image to show?

Viewing 8 replies - 1 through 8 (of 8 total)
  • <?php

    $image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>

    if ($image) {
    <div id=”featuredimage” style=”background-image: url(‘<?php echo $image; ?>’)”>
    </div>
    <?php } ?>

    Thread Starter hrrubin

    (@hrrubin)

    Thank you. I will try it.

    Thread Starter hrrubin

    (@hrrubin)

    It did not seem to work for me. I got instead a php error saying that

    <?php } ?> is wrong, “}” is unexpected.

    <?php
    
    $image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
    
    if ($image) { ?>
    <div id="featuredimage" style="background-image: url('<?php echo $image; ?>')">
    </div>
    <?php } ?>

    [Moderator Note: Please post code & markup between backticks or use the code button. Your posted code may now have been permanently damaged by the forum’s parser.]

    Try like this! I forgot to close the tag

    Thread Starter hrrubin

    (@hrrubin)

    It’s still giving me the php error.

    Moderator Jose Castaneda

    (@jcastaneda)

    THEME COFFEE MONKEY

    Have you tried using has_post_thumbnail instead?

    It would look something like:

    if ( has_post_thumbnail() ) {
        // Code to run
    }

    code by @gcarrenos repaired:

    <?php
    $image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
    
    <?php if ($image) { ?>
    <div id="featuredimage" style="background-image: url('<?php echo $image; ?>')">
    </div>
    <?php } ?>
    Thread Starter hrrubin

    (@hrrubin)

    Thank you alchymyth. This works 🙂

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Hide featured image if there isnt' one’ is closed to new replies.