Forum

Thread tagged as: Question, Shop

Check for sub-categories

I am trying to set up a new Perch Shop in Runway, which uses sub-categories for organising the products (not tried this before). My category tree looks like:

Products
|- Things
|- Whatsits
|-- Ordinary Whatsits (sub-category of Whatsits)
|-- Special Whatsits (sub-category of Whatsits)

On my main Products page I want to display two links, one for Things and one for Whatsits. If a person clicks on Things then then get shown the products in that category. If they click on Whatsits they then get shown the links for the sub-categories within that category, which in turn when clicked on show the products in those sub-categories.

This is my Products page so far:

  if(perch_get('category')) {
    perch_shop_products([
      'category' => 'products/' . (perch_get('category'))
    ]);
  }

  else {
    perch_categories([
      'set' => 'products',
      'template' => 'category-links',
    ]);
  }

And my category-links template:

<perch:before><ul></perch:before>
  <perch:if id="catDepth" value="1">
    <li><a href="/products?category=<perch:category id="catSlug" type="slug" for="catTitle" />"><perch:category id="catTitle" type="smarttext" label="Title" required="true" /></a>
    </li>
</perch:if>
<perch:after></ul></perch:after>

This is working ok to just show the top-level categories, but is then showing all products in the top level category even for the Whatsits category. How can I check if there are sub-categories, and do something different? I am stumped.

Thanks as always for any help

Mike

Mike Harrison

Mike Harrison 37 points

  • 4 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

Are you asking how to structure your logic, or how to output particular content from the CMS? I'm not sure which.

Duncan Revell

Duncan Revell 78 points
Registered Developer

Mike,

I suspect you may need to add another test in here:

if(perch_get('category')) { 

$subcats = perch_categories([ 
'set' => 'products', 
'filter'=>[
['filter'=>'catPath',
'match'=>'contains',
'value'=>'products/'. (perch_get('category') . '/?',],
['filter'=> 'substr_count(catTreePostion,"-")',
'value'=>2,
'template'=>'some_other_template.html',],
],
'skip-template' => true,
'return-html'=>true,
]); 

if (PerchUtil::count($subcats)) {
echo $subcats['html'];
} else {
perch_shop_products([ 
'category' => 'products/' . (perch_get('category')) 
]); 
}
} 

Using a filter on catTreePosition is basically the same as testing catDepth (which you can only use in a template).

Thanks Duncan that's a great help - I hadn't looked at using catTreePosition, and counting the dashes is a neat way of doing it :)