Blog-like list of posts - better way to do this?

Hi all there,

I’m currently playing around with Kirby to find out if might replace my WordPress installation.

Right now, each post is assigned to exactly one category, but the categories might be nested (max. 3 levels deep).

To find the latest posts for each category (and the start page), I created a recursive function to get all children, but this seems like wasting a lot of ressources just to get the latest n posts.

	function getAllChildren($start) {

		$children = new Pages();

		foreach ($start->children() as $child) {

			$children->add($child);

			if ($child->hasChildren()) {

				$children->add(getAllChildren($child));
			}
		}

	return $children;
	}

	$posts = getAllChildren($site);

	foreach ($posts->sortBy('published', 'desc') as $post) {
		print $post->title();
	}

Is there a better (Kirby?) way to do this?

Thanks!

If I understand correctly, you have sorted your posts under category pages rather then assigning categories to posts?

In any case, you can access all pages of a given page with $page->index(), which gives you a flat collection of pages you can then filter and sort as desired. I would filter them by template to exclude the category page in the tree, e.g.

$somecategoryPosts = new Pages();
if ($page = page('somecategory') {
  $somecategoryPosts = $page->index()->listed()->template('blogpost');
}

where template('blogpost') is short for filterBy('template', 'blogpost').

To start at the site level, you can use $site->index(), which is, however, not recommended for large sites.

Hi texnixe,

thanks for the fast reply and showing a much better way to solve my problem.

In WordPress there’s just a category assigned to each post using the standard widget, but when clicking on a category in the frontend, WordPress delivers a list of all posts belonging to this category.

I was thinking about creating some sort of “category”-template to simulate the WordPress URL-scheme “/category/categorya/categoryb/”, so “category.txt” (with corresponding template “category.php”) would reside in each “category” folder (categorya, categoryb, etc) and show just a list of the included (nested) child pages.

As far as I understand, the “/category” itself could be best solved with routing.

Yes, you either actually have category pages, or you create routes for your category patterns.

After all, WordPress doesn’t do anything else with the difference that the routes are created automatically.