pipit_category_get_id()
pipit_category_get_id()
takes the returned category source (typically when you use the skip-template
option) and returns the category ID. The function is similar to pipit_category_get_path()
, but returns the category ID.
Perch in some cases stores categories by their IDs and in other cases by their category paths. A common use-case for needing the category ID instead of the path is for rendering templates with perch_template()
.
pipit_category_get_id($source);
<perch:content id="name" type="text" label="Product Name">
<perch:content id="slug" type="slug" for="name">
<perch:categories id="categories" set="products" label="Categories" />
$product = perch_collection('Products', [
'template' => 'products/detail.html',
'skip-template' => true,
'return-html' => true,
'filter' => 'slug',
'value' => 'my-product',
]);
if(isset($product[0])) {
array_walk($product[0]['categories'], function(&$category) {
$category = pipit_category_get_id($category);
})
// output rendered content/products/detail.html
echo $product['html'];
// render another template using the same product data without making another database query
perch_template('content/products/another_template.html', $product[0]);
}
The function only attempts to retrieve the category ID if $source
is not numerical. If $source
is numerical, the function will return the numerical value without checking whether it is in fact a category ID. This is because $source
is expected to be either a category ID e.g. 34
or a category path products/shoes/
.