Pipit v0.3: Categories functions
The Pipit app v0.3 comes with 3 new functions that make working with categories a little easier.
Output a Category Set
Currently, there’s no Perch function for outputting a Category Set. That’s why I wrote pipit_category_set(). The function uses the same samiliar syntax you’re familiar with:
pipit_category_set('products');
$set_html = pipit_category_set('products', [], true);
echo $set_html;
$set = pipit_category_set('products', [
'skip-template' => true,
'return-html' => true,
]);
echo $set['html'];
I think Perch will eventually ship with a built-in function for this, but for now this should fill in the gap and allow you to use it in your projects.
Category path vs ID
There are instances when you need a category path and others when you need a category ID. For example, for category filtering you need to use category paths:
perch_collection('Products', [
'category' => ['products/shoes/', 'products/socks/'],
]);
However, to render a template with a function like perch_template()
or pipit_template()
, you need category IDs:
perch_template('content/example.html', [
'title' => 'Example template',
'categories' => [12, 34]
]);
Additionally when you use the skip-template
option (when using functions like perch_collection()
and perch_blog_custom()
) and you have a categories field, Perch may return the categories as IDs or paths.
$products = perch_collection('Products', [
'skip-template' => true,
'filter' => 'slug',
'value' => 'my-product',
]);
foreach($products as $product) {
foreach($product['categories'] as $category) {
// $category can be a path e.g. products/shoes/
// or it can be an ID e.g. 34
}
}
I don’t know why this happens, but as you can imagine it can be an inconvenience. So here are a couple of helper functions to use in these cases:
$products = perch_collection('Products', [
'skip-template' => true,
'filter' => 'slug',
'value' => 'my-product',
]);
$categories = array();
foreach($products as $product) {
foreach($product['categories'] as $category) {
$categories[] = pipit_category_get_path($category);
}
}
// similar products
perch_collection('Products', [
'category' => $categories,
'filter' => 'slug',
'match' => 'neq',
'value' => 'my-product',
]);