• I’ve been using the the following code to get the url of post thumbnails.

    <?php $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,'large'); $image_url = $image_url[0]; ?><?php echo $image_url;?>

    It works great, and below is how I use it in my theme.

    <?php $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,'large'); $image_url = $image_url[0]; ?>
    
    <img src="<?php echo $image_url;?>" />

    The problem with this is when there is no post thumbnail available it still return the img tag without a URL since there is none available. I tried wrapping in the following code but it doesn’t work:

    <?php if ( has_post_thumbnail()) : ?>
    
    <?php $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,'large'); $image_url = $image_url[0]; ?>
    
    <img src="<?php echo $image_url;?>" />
    
    <?php endif; ?>

    How can I make it so that nothing is displayed, when there is no post thumbnail available?

    Please keep in mind I’m a complete rookie to WordPress and PHP.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hey Chozen,

    I’m pretty new to wordpress, so maybe there’s a better way to solve this.. but I think this should work (untested):

    <?php $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,'large');
    
    if(isset($image_url[0])){
        echo '<img src="'.$image_url[0].'" />';
    }
    
    ?>

    Simple check if $image_url[0] is set… ??

    Mark

    Thread Starter Glen

    (@chosen1234)

    Thanks that worked perfectly, been trying to resolve that for days.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Post Thumbnail URL with Conditional tags’ is closed to new replies.