Hi,
I have a parent Case Studies page, on the blueprint for which I have a structure for specifying categories:
categories:
label: Categories
type: structure
fields:
category:
label: Category
type: text
The children of this page are the individual case studies, on which the editor can select one or more categories for the study, using this multiselect:
categories:
label: Categories
type: multiselect
required: true
options: query
query:
fetch: page.parent.categories.toStructure
text: "{{ structureItem.category }}"
value: "{{ structureItem.category.slug }}"
This then forms the basis of a filtering method. I now need to list the individual case studies on the main case study page, and as part of that listing I would like to include the first category selected for that case study. I have tried this:
<?php $caseStudies = $page->children()->listed(); ?>
<?php foreach ($caseStudies as $caseStudy): ?>
<?= $caseStudy->categories()->split()[0] ?? ''; ?>
<?php endforeach ?>
Which sort of works, in that it outputs the slug (e.g. turnkey-solutions). I need to output the actual category name (e.g. Turnkey Solutions). Is it possible to find this somehow?
Thanks for any help
Yes, thatβ s possible if not very straightforward.
<?php
$categories = $page->categories()->toStructure();
$caseStudies = $page->children()->listed();
?>
<?php foreach ($caseStudies as $caseStudy): ?>
<?php
$category = $categories->filter(function($item) use($caseStudy) {
return $item->category()->slug() === $caseStudy->categories()->split(',')[0] ?? '';
})->first();
echo $category;
?>
<?php endforeach ?>
Thanks for the quick reply! Unfortunately I am not getting anything output with that code - no error, just no output. I have had a look and canβt work out what I might need to change.
Could you please show me what you get in your content file for the structure field with the categories?
Sure, it looks like this:
Categories:
-
category: Mezzanine floor
-
category: 'Pallet racking & inspections'
-
category: Shelving
-
category: Dilapidations
-
category: 'Removals & relocations'
-
category: Turnkey solutions
-
category: Partitioning
-
category: Dynamic solutions
-
category: 'Design & fit out'
Ok, and the child pages then have something like
category: mezzanine-floor, shelving, removals-relocations
?
This is an example from a child page:
----
Categories: pallet-racking-inspections, turnkey-solutions, dynamic-solutions
----
Ok, Iβve found the issues:
<?php
$categories = $page->categories()->toStructure();
$caseStudies = $page->children()->listed();
?>
<?php foreach ($caseStudies as $caseStudy): ?>
<?php
$category = $categories->filter(function($item) use($caseStudy) {
return $item->category()->slug() ->value() === ( $caseStudy->categories()->split(',')[0] ?? '' );
})->first();
if ( $category ) {
echo $category->category();
}
?>
<?php endforeach ?>
That works perfectly. Awesome, thank you @texnixe !
1 Like