Jump to content

How to show a list of children, grouped by category title?


Recommended Posts

Posted

I have a page with children like this:

Music Samples

  Fugue in D Minor

  La Cucaracha

  Rock You Like A Hurricane

...and each child has a category (using a page select field), in this example Classical, Ethnic, and Rock.

How would I display a list like this?

CLASSICAL

  Fugue in D Minor

ETHNIC

  La Cucaracha

ROCK

  Rock You Like A Hurricane

Thanks!

Posted

if you have your categories as pages under a page /categories/ you could loop them and output examples having this category. In this example we assume "category" is the name of the page field in your sample.

<?php
// get all categories
$categories = $pages->get("/categories/")->children;
echo "<ul>";
// loop categories
foreach($categories as $cat) { 
   echo "<li>{$cat->title}";
   // find me all samples having the current category
   $samples = $pages->get("/music-samples/")->find("category=$cat");
   // if any found output them 
   if( count($samples) ) {
       echo "<ul>";
       foreach($samples as $sa) {
           echo "<li>$sa->title</li>";
       }
       echo "</ul>";
   }
   echo "</li>";
}
echo "</ul>";

...accidently submited before finishing code :D

Posted

Thanks, Soma! I will have a separate categories page/children so that seems like it will work great. Thank you.

Posted

Here's another way you could do it too. Though I'd probably use Soma's more straightforward approach unless you are dealing with a large quantity of categories. The reason for that is that this approach (below) is technically a little faster since it's one samples query to cover all categories rather than one samples query per category. But I think Soma's method is easier to follow with more straightforward logic.  

<?php
$cats = $pages->find("parent=/categories/"); 
$samples = $pages->find("parent=/music-samples/, category=$cats, sort=category.name, sort=name"); 
$last = null;
foreach($samples as $s) {
   if($s->category !== $last) {
       if($last) echo "</ul>";
       echo "<h2>{$s->category->title}</h2><ul>";
   }
   echo "<li>{$s->title}</li>";
   $last = $s->category; 
}
echo "</ul>";

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...