0
votes

My WordPress Blog consists of the following snippet:

<?php
    $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    if (count($images) > 0) { ?>

       <div class="image-holder">
       <a href="<?php the_permalink(); ?>"><img src="<?php bloginfo('template_directory') ?>/javascript/timthumb.php?src=<?php echo $images[0]; ?>&amp;h=320&amp;w=630&amp;zc=1" alt="<?php the_title();?>"  /></a>             
       </div>

    <?php }
?>

This displays a title image (featured image) on top of the actual content and uses timthumbb to resize it. All is fine here, however it shows a broken img src if there is no defined featured image. Is there a way to edit this in order to only display the image if there is actually one present?

4

4 Answers

0
votes

I used this and it works fine:

// get the ancestors
$familyTree = get_ancestors($post->ID, 'page');
array_unshift($familyTree, $post->ID); //add the current page to the beginning of the list

// loop through the family tree until you find a result or exhaust the array
$featuredImage = '';
foreach ($familyTree as $family_postid) {
    if (has_post_thumbnail($family_postid)) {
        $featuredImage = get_the_post_thumbnail($family_postid, 'full');
        // the 'full' argument tells WordPress not to re-size the image to thumbnail dimensions
        break;
    }
}

// if the page has a featured image then show it
echo ($featuredImage ? $featuredImage : "");

it also applies the featured image to child pages unless the child page has it's own featured image, not sure if you want that but shouldn't be too difficult to not show anything if there is no featured image.

0
votes
Try using this logic

<?php

    if($images[0]!='')
    {
     <div class="image-holder">
           <a href="<?php the_permalink(); ?>"><img src="<?php bloginfo('template_directory') ?>/javascript/timthumb.php?src=<?php echo $images[0]; ?>&amp;h=320&amp;w=630&amp;zc=1" alt="<?php the_title();?>"  /></a>             
           </div>
    }

    ?>
0
votes

if there is only one image, you can use

if ($images[0]!='') {
0
votes

You can use the function has_post_thumbnail() to check whether the post has a featured image or not.

Usage:

    $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    if (count($images) > 0) { ?>

       <div class="image-holder">
       <a href="<?php the_permalink(); ?>"><img src="<?php bloginfo('template_directory') ?>/javascript/timthumb.php?src=   <?php echo $images[0]; ?>&amp;h=320&amp;w=630&amp;zc=1" alt="<?php the_title();?>"  /></a>             
       </div>

    <?php }
} ?>