Jump to content

skip image


Marty Walker
 Share

Recommended Posts

Hi everyone,

I've got a news section setup on a site in development. I want to pull the most recent three news items onto the home page. All good except for a small image issue. I have an image field in the news entry and below I'm calling the first one there for the thumbnail. What I'm stuck with is how to skip/ignore that instruction if there's no image. Most of the time there will be an image but I want to cover myself in case there's not.

Regards

Martin

<?php
$today = time();
$news = $pages->get("/news-and-events/")->find("limit=3, template=news-entry, sort=-publish_date, publish_date<$today");
foreach($news as $newsitem) {
$newsimage = $newsitem->images->first();
    if(!$newsimage) continue; // NOT SURE WHAT TO DO HERE
$newsthumb = $newsimage->size(80,80);
    if(!$newsthumb) continue; // NOT SURE WHAT TO DO HERE
echo "<dl class='clearfix'>
		<dt><a href='{$newsitem->url}'>{$newsitem->title}</a></dt>	
		<dd class='image'><img src='{$newsthumb->url}' alt='{$newsitem->title}' width='80' height='80' /></dd>
		<dd>{$newsitem->summary}</dd>	
	</dl>";
	}
Link to comment
Share on other sites

Hey! This should work :)

  <?php
    if(count($newsitem->images)) {
      $newsimage = $newsitem->images->first();
      $newsthumb = $newsimage->size(80,80);
    }else{
      // expand '$newsthumb' with some fallback image?
    }
    echo "<dl ... >";
Link to comment
Share on other sites

Simply; You call 'url' property of image object, whether you have the object initialized (i.e. if page has images), or not (the second part, where you should set fallback). If it's the latter, it will fail, because it seems you don't know how to create fallback image :)

You have multiple options here; either create some fallback page (e.g. '/fallback'), which wil have the fallback image prepopulated – in this case, in my previous code, the second part will be:

// expand '$newsthumb' with some fallback image?
  $newsthumb = $pages->get('/fallback')->images->first()->size(80,80);

or, more direct approach is to add another variable, e.g. '$newsthumburl', and either populate it if image is found or hardset it to fallback/placeholder image if not:

  <?php
    if(count($newsitem->images)) {
      $newsimage = $newsitem->images->first();
      $newsthumburl = $newsimage->size(80,80)->url;
    }else{
     $newsthumburl = '/path/to/my/fallback_image.png';
    }
    echo "<dl ... {$newsthumburl} ... >";
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...