Displaying product items from multiple folders using the loop

Hi there, This code will display the products items from the soap folder which lives inside the content folder. My question: How can I display product items from other folders e.g. from the toothbrush folder and the shampoo folder? I know I can repeat this code by copying it and changing the variable $soap to say $toothbrushes but this is not a good solution really.

  <article class="products">
    <?php if ($p = page('soap')) : ?>
  <?php foreach ($p->children() ->limit(9) as $soap): ?>
  <div class="products-box">
    <a href="<?= $soap->url() ?>">
      <?php if ($image = $soap->image()): ?>
      <img src="<?= $image->url() ?>">
      <?php endif ?>
    </a>
    <div class="products-box-title">
      <h3><?= $soap->title()->html() ?></h3>
    </div>
  </div>
  <?php endforeach ?>
<?php endif ?>
  </article>
</div>

Grateful if you can point me in the right direction.

In this case, $pages->find(...), but I’d recommend you put all products types into a subfolder products instead of folders on the first level.

Thank you. So like this, but with the various products folders that live inside the content folder being placed inside a folder called subfolder (which will also live inside the content folder)?

<article class="products">
  <?php if ($p = page('subpage')) : ?>
    <?php foreach ($p->children()->limit(9)->find('soap', 'toothbrush', 'cremes') as $subpage): ?>
      <div class="products-box">
        <a href="<?= $subpage->url() ?>">
          <?php if ($image = $subpage->image()): ?>
            <img src="<?= $image->url() ?>">
          <?php endif ?>
        </a>
        <div class="products-box-title">
          <h3><?= $subpage->title()->html() ?></h3>
        </div>
      </div>
    <?php endforeach ?>
  <?php endif ?>
</article>

What I wrote above were two different things:

Either, you use find() to get a collection of those product pages (soap, etc).

Or, you move the different product categories into a products subfolder, then loop through the children of the subfolder.

Anyway, in both cases, you need two loops: 1 for the categories pages, one for the children of each category.

And note, that you always use limit() last, not in the middle of your query.

1 Like

Thank you :+1: