Categories in post lists and individual post

Hi everyone, I’m trying a whole lot to add categories to what I’m working on. I did manage to have different filter my posts but so far I cant for dear life lists the category of each post.

This is what I’m working with:

return function($page) {
    // fetch the basic set of pages
    $posts = $page->children()->listed()->flip();

    // fetch all categories
    $categories = $posts->pluck('categories', ',', true);

    // add the category filter
    if($category = param('category')) {
    $posts = $posts->filterBy('categories', $category, ',');
    // apply pagination
    $posts   = $posts->paginate(5);
    $pagination = $posts->pagination();

    return compact('posts', 'categories', 'category', 'pagination');

Where I’m trying to display tags

<section class="categories">
<a href="<?= $page->url() ?>">All</a>
<?php foreach($categories as $category): ?>
    <a href="<?= url($page->url(), ['params' => ['category' => $category]]) ?>" <?php e($category === param('category'), 'class="active"', '')  ?>><?= html($category) ?></a>
	<?php endforeach ?>

<?php foreach($posts as $post): ?>
	<a href="<?= $post->url() ?>"><h3><?= $post->title()->html() ?></h3></a>
		<p>On <time><?= $post->date() ?></time>, listed under 
		<span class="category">
// this is where I'm trying to display categories
	<?php endforeach ?>
<?php snippet('pagination', ['pagination' => $posts->pagination()]) ?>

Please believe me, I searched everywhere but I don’t understand what I must do to get this working.

Thank you

// fetch single post categories, split into array
$postCats = $post->categories()->split();
// then loop through the categories

Thank you!

Am I doing this right?

<?php $postCats = $post->categories()->split(); ?>
<?php foreach($postCats as $postCat): ?>
    <?= $postCat->html() ?>
<?php endforeach ?>

I’m trying to link the slug as well if that matters similar to what I have on the separate categories section.
I’m sorry if it’s trivial but I got no idea what I’m doing. I’m trying to learn as I go from scratch. I only know html and css

No, you can’t call the html() method on a string, should be:

<?php foreach($postCats as $postCat): ?>
  <?= html($postCat) ?>
<?php endforeach ?>

In a link with filter param:

<?php foreach($postCats as $postCat): ?>
  <a href="<?= $page->url(['params' => ['category' => $postCat]]) ?>"><?= html($postCat) ?></a>
<?php endforeach ?>

Thank you so so much!!! This was the final piece of my template. I managed to build my entire site with no php knowledge and just 2 questions asked. I don’t know how I did it, but you just saved me.

Thank you again!!

1 Like