Hi all
I would like to filter my blog content per category. I’ve been following the filtering by routes guide and I can’t get it to work…
Any help is appreciated!
This is my code
article contains field
----
Category: Sport
----
route in config.php
'routes' => [
[
'pattern' => 'magazin/category/(:any)',
'action' => function ($category) {
return Page::factory([
'slug' => $category,
'template' => 'category',
'model' => 'category',
'content' => [
'title' => 'Results for ' . ucfirst($category),
]
]);
}
]
]
link to page
<a href="<?= $site->url() . '/magazin/category/' . urlencode($article->category()->slug()) ?>"><?= $article->category() ?></a>
controller category.php
<?php
return function($kirby, $site, $pages, $page) {
$shared = $kirby->controller('site' , compact('page', 'pages', 'site', 'kirby'));
$category = urldecode($page->slug());
$articles = page('magazin')->children()->filterBy('category', $category, ',');
return A::merge($shared , compact('category', 'articles'));
};
?>
template category.php contains
<?php if ($articles->isNotEmpty()) : ?>
<?php foreach ($articles as $article) : ?>
<article>
<h2><?= $article->title()->html() ?></h2>
<?= $article->text()->kt() ?>
<ul>
<?php foreach ($article->category()->split(',') as $category) : ?>
<li><a href="<?= page('magazin')->url() . '/magazin/' . esc($category, 'url') ?>"><?= $category ?></a></li>
<?php endforeach ?>
</ul>
</article>
<?php endforeach ?>
<?php else : ?>
<div>No results for category <?= $category ?></div>
<?php endif ?>
So what I want to achieve is to filter content by category and the url to be website.com/blog/sport, not website.com/blog/category/sport (my blog is called ‘magazin’). Currently when I open that url, I get the text ‘No results for sport’.
What am I doing wrong?