Jump to content

Show placeholder image if image field is lacking


Jon E
 Share

Recommended Posts

Hi,

Sorry this is probably very basic logic, but I wondered what you would suggest if my code is:

<?php
$features = $pages->find("template=portfolio, limit=4, sort=-date");
foreach($features as $feature) {
$thumb = $feature->thumbnail->size(244,244);
  echo "<li>" .
    "<a href='{$feature->url}'><div id='explore_thumb'><img src='{$thumb->url}'></div>" .
    "<h3>{$feature->title}</h3>" .
    "<h4>{$feature->summary}</h4></a>" .
    "</li>";
}
?>

And I want to output a placeholder image in the instance that a thumbnail isn't uploaded...

Thanks,

Jon

Link to comment
Share on other sites

<?php
$features = $pages->find("template=portfolio, limit=4, sort=-date");
foreach($features as $feature) {
  $thumb = $feature->thumbnail ? $feature->thumbnail->size(244,244)->url : "[url to the placeholder]"; // if no thumbnail, replace by placeholder
  echo "<li>" .
     "<a href='{$feature->url}'><div id='explore_thumb'><img src='{$thumb}'></div>" . //changed from $thumb->url to only $thumb
     "<h3>{$feature->title}</h3>" .
     "<h4>{$feature->summary}</h4></a>" .
  "</li>";
}
?>
  • Like 2
Link to comment
Share on other sites

It's pretty obvious because of diogo's code comment but just in case you're wondering; he's using a so called ternary operator. Which is basically the same as this If/Else statement:

if($feature->thumbnail) {
 $thumb = $feature->thumbnail->size(244,244)->url;
}else{
 $thumb = "[url to the placeholder]";
}
  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...