sarytash
sarytash

Reputation: 171

Get rid of broken image in foreach loop?

A thumbnail image, 'smallthumb' is retrieved with get_post_meta looping an array with foreach.

Is it possible to display the image only if there is a thumbnail image? At the moment IE and FF display a broken image if there is no value for the 'smallthumb' image.

<?php
  if(count($ids)){
    echo '<div id=read-more-widget>
    <div class="read-more-header">Read more</div>
    <ul class="read-more-links">';
  foreach($ids as $id){
    echo '<li><a href="'.get_permalink( $id ).'">'.get_the_title( $id ).'</a>
    <a href="'.get_permalink( $id ).'">
    <img class="small-thumb" src="'.get_post_meta( $id, 'smallthumb', true ).'">
    </a><p class="read-more-entry">'.get_post_meta( $id, 'entry', true ).'</p></li>';
    }
  echo "</ul></div>";
 }
?> 

Upvotes: 1

Views: 235

Answers (1)

James Brooks
James Brooks

Reputation: 658

I'm not sure exactly how your code works, but would removing the img tag alltogether be a viable solution? e.g.

<?php
  if(count($ids)){
    echo '<div id=read-more-widget>
    <div class="read-more-header">Read more</div>
    <ul class="read-more-links">';
  foreach($ids as $id){
    echo '<li><a href="'.get_permalink( $id ).'">'.get_the_title( $id ).'</a>
    <a href="'.get_permalink( $id ).'">

    <?php if ($smallthumb = get_post_meta( $id, 'smallthumb', true)) { ?>
      <img class="small-thumb" src="'.$smallthumb.'">
    <?php } ?>

    </a><p class="read-more-entry">'.get_post_meta( $id, 'entry', true ).'</p></li>';
    }
  echo "</ul></div>";
 }
?>

The exact solution will need to be updated slightly depending on what get_post_meta( $id, 'smallthumb', true) is likely to return.

Upvotes: 1

Related Questions