Jump to content

Displaying a Random Image from any web page


mcgarriers
 Share

Recommended Posts

Does this:

$sub_image = $pages->get("has_parent.id=$sub->id,template=product, sort=random")->product_images->find('tags=prod')->getRandom();

work? (You may want to also include a "product_images.tags=prod" subfield selector for the pages in case you have pages without a production ready image)

  • Like 1
Link to comment
Share on other sites

18 hours ago, opalepatrick said:

$sub_image = $pages->get("has_parent.id=$sub->id,template=product, sort=random")->product_images->getTag('prod')->getRandom();

one problem with this is that i think you wanted to use findTag('prod')->getRandom()   (?)

 

 

 

 

 

Link to comment
Share on other sites

6 hours ago, opalepatrick said:

That returned a non-object error when I tried to access the variable next line

I think the problem is something @BitPoet mentioned above: you want to be sure the matched page has some images tagged "prod" before you try and get one of them.

As @Macrura says, find('tags=prod') and findTag('prod') will do the same thing.

// either...
$sub_image = $pages->get("has_parent.id=$sub->id, template=product, product_images.tags=prod, sort=random")->product_images->find('tags=prod')->getRandom();
// or...
$sub_image = $pages->get("has_parent.id=$sub->id, template=product, product_images.tags=prod, sort=random")->product_images->findTag('prod')->getRandom();
// then...
if($sub_image) {
    // whatever...
}

Edit: If it's possible that no pages have any images tagged "prod" (and it's probably a good idea in any case) then you should actually break this into two steps to make sure your $pages->get() operation has returned a page.

$sub_image_page = $pages->get("has_parent.id=$sub->id, template=product, product_images.tags=prod, sort=random");
if($sub_image_page->id) {
    $sub_image = $sub_image_page->product_images->find('tags=prod')->getRandom();
}
if($sub_image) {
    // whatever...
}

 

  • Like 1
Link to comment
Share on other sites

Thanks Robin S, Macrura and BitPoet... Breaking it down as per last edit was the solution... 

$sub_image_page = $pages->get("has_parent.id=$sub->id, template=product, product_images.tags=prod, sort=random");
if($sub_image_page->id) {
  $sub_image = $sub_image_page->product_images->find('tags=prod')->getRandom();
  if($sub_image) {
    echo "<img src='<?=$sub_image->width(300)->url?>' />";
  }
  else {
    echo "<p>No prod tagged images</p>";
  }
}
else {
  echo "<p>no pages</p>";
}

 

  • Like 1
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...