Jump to content

Get images from multiple pages by tag, then display one image randomly


Go to solution Solved by LedZepmann,

Recommended Posts

Hello All! This is my first post here and am a newbie with PW.  So far I've been able to accomplish everything I've wanted to do dynamically in my first PW site, but ran into a big snag yesterday.

Ok here's the setup:  I have on my site 4 pages that deal with separate plumbing services. We offer a discount coupon for each service. For each service, I am displaying it's coupon image in the sidebar. Each coupon image resides in the images field of the individual rootParent parent services page, and each image has a tag of "coupon" assigned to it. So for example, I have a rootParent level "Drain Cleaning" page and it is in this page's images field that the Drain Cleaning coupon image resides with the tag "coupon."  The next coupon resides in the images field for my rootParent "Sewer Cleaning" page, and so on.

For each service page, I have some Hanna Code I wrote to include the coupon image in the sidebar of the rootParent and all of it's children:

$coupon = $page->rootParent->images->getTag('coupon');

This works great!  Now, here's my problem... For pages other than the service pages, like form confirmation pages, the Contact Us page, etc., I still want to display a coupon image in the sidebar, but I want to grab a random coupon image and display it.  So far, I have not found a way to successfully scan all page's images field, grab the images with the tag of coupon, then display a random image.  Here is the code I've come up with so far that is not working:

First, build the array of pages containing an image with the tag of coupon (this works):

$couponpages = $pages->find("images.tags=coupon");

Next, get the images tagged coupon from the array of pages containing them (this is where the code breaks and throws an error):

$coupons = $couponpages->images->getTag("coupon");

The error reads: "Fatal error: Call to a member function getTag() on a non-object." 

Beyond that, I would then want to fetch a random image and display it:

$coupon = $coupons->getRandom();
echo "<img alt='{$coupon->description}' src='{$coupon->url}' />";

If anyone can help me solve this it would be most appreciated!

Thanks,

Dave

Link to post
Share on other sites

Hold the phone... I just solved it!  Just had to reverse step two and step three!  So Get a random page from the array first, then display the image with the tag of coupon:

$couponpages = $pages->find("images.tags=coupon");
$coupons = $couponpages->getRandom();
$coupon = $coupons->images->getTag("coupon");
echo "<img alt='{$coupon->description}' src='{$coupon->url}' />";

Success!

  • Like 1
Link to post
Share on other sites

Hi Dave,
 
Welcome to PW and the forums... :-)
 
Glad you sorted it out but would like to suggest you do it differently...assuming I understood the question correctly...
 
If all you want is to grab one random image from a coupon page, there is probably no need to find several pages first. Why not grab ONE random page instead (one containing your coupon images) and display its coupon image? Assuming that a coupon page contains other images as well but you are only interested in the coupon image (i.e. tagged 'coupon'), something like this maybe...

//we only get one random coupon page (we use 'get' rather than 'find')
$couponimage = $pages->get("template=service-pages, sort=random")->images->getTag('coupon');

Edit:

This code assumes there will always be a coupon image in those service pages.

Edited by kongondo
  • Like 5
Link to post
Share on other sites
//we only get one random coupon page (we use 'get' rather than 'find')
$couponimage = $pages->get("template=service-pages, images.tags=coupon, sort=random")->images->getTag('coupon');

@Kongondo: Your code together with the pages selector from Dave should be a solid solution. - But haven't tested.

@Dave: Welcome.  :)

  • Like 3
Link to post
Share on other sites

Hi Kongondo,

Thanks so much for your reply! I tried your code and it didn't work for me, most likely because I have a common template for all internal pages named "content-page" and not all pages in the site have a coupon image in them.  However, your code is a great example of using selectors to condense the steps I took  :)  I'm sure it would work if I had a separate template just for the service pages.  Thanks for your input - it helps me a lot!

  • Like 1
Link to post
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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By spercy16
      These issues should be fairly easy for any intermediate to advanced ProcessWire developer to answer. I'm new to PHP and relatively new to ProcessWire and just need a bit of help. What I'm trying to do is bring in a couple of cards from my Projects page to display on my home page. I finally got the code right to bring in the cards but right now they're using my original images instead of my resized "variations". So firstly, I would like to know how to reference the variations of my images instead of using the original. Secondly, I need to grab only four of the cards from the Project page and not import in all ten. It should be just two small changes to my code to do these things (I would imagine). Here is the code I currently have for that section:
      <?php // https://processwire.com/api/arrays/ // check if the array of images has items if (count($pages->get("/projects/")->images)) : // get array of images from the field $images = $pages->get("/projects/")->images; $count = 0; // iterate over each one foreach ($images as $image) : $count++; $sectionText = $pages->get("/projects/")->get("paragraph_$count"); $img = $image; $buttonCode = $pages->get("/projects/")->get("url_$count"); ?> <span id="card<?php echo $count?>" class="card"> <img class="cardThumb" src="<?php echo $img->url; ?>" alt="<?php echo $image->description; ?> Thumbnail" /> <div class="cardBody"> <div class="cardText"> <h2><?php echo $img->description; ?></h2> <?php echo $sectionText; ?> </div> <div class="primaryBtn"> <a href="https://www.paypal.com/donate?hosted_button_id= <?php echo $buttonCode; ?> &source=url"> <button> <i class="fas fa-donate"></i> Donate </button> </a> </div> </div> </span> <?php endforeach; endif; ?> Thanks in advance for any help!
    • By skeltern
      WebP image support is great and works fine. But once created I've issues to get rid of all API generated WebP variations.
      The backend image field variations "Delete" works and I can remove all variations JPEG plus WebP. Image list is clean but all WebP API variations are still stored in file system (for instance files/12345/84.900x675.webp etc). I can only use ImageSizer with temp 'force' option to request fresh WebP variations or have to delete WebP files from folders. No other way so far. Tested with 2 sites and latest master PW 3.0.165.
      Is there somewhere a "magic button" or config/setup thing to solve my sticky WebP issue?
    • By psy
      I've searched, and maybe missed, the solution. I have a 'normal' images field and uploading images with a file size greater than 10Kb is fine. Any image size smaller results in the never-ending spinner and no upload.
      No min/max width/height set on image uploads in admin, ie just the defaults.
      Any ideas on how to fix?
      Using:
      PW: 3.0.175
      PHP: 7.3
      Marking it as "Resolved" rather than "Solved" as it auto-magically fixed itself. No idea whether PW, PHP, or just an internet hiccough... All good now 🤞
    • By totoff
      Dear all,
      tomorrow I'll have to introduce some editors on how to upload and edit images in image fields in Processwire. The site in question is quite image rich and I've spent some time to serve the appropriate images via scrcset already cropped for different screen sizes.
      However, the backend offers a lot of possibilities to manipulate images and most of them I'm not familiar with because as a developer I've never spent much thinking on what all the features might be good for … Yet I'm concerned that my editors work on images in the backend may interfere with my optimization strategies in the templates.
      Is there a general rule of thumb what content editors should do or not do with images in order not to break srcset strategies etc.? Maybe there is already a source of information you could point me to?
      Your recommendations are much appreciated!
    • By totoff
      Dear all,
      I'm upgrading an older side with the new custom fields for images feature as of 3.0.142. My image field is set to "Automatic" and holds a bunch of images together with their respective description on each page. New custom fields include "caption" among others and to make my live easier I I'm trying to populate "caption" with the value from the (default) description field. But unfortunately I can't seem to find out how to save the newly set values. This is my code:
      <?php foreach (page()->images as $image) { $image->set('caption', $image->description); bd($image->caption); echo files()->render("markup/views/view-card-image-fancybox.php", array('image'=>$image)); } ?> <?php $page->save(); bd($page->save()); ?> This sets the value as intended (see screenshot) but doesn't save it permanently to the database. What am I doing wrong?
      Thanks!
       

×
×
  • Create New...