Saving Categories, How to return the category value on the frontend?

We use the following code.

category:
      label: Category
      type: select
      options:
        news: News Article
        architecture: Architecture
        photography: Photography
        3d: 3D
        web: Web

in our yaml. The admin selects an option.

It stores the id in our text file

Category: news

We want to return News Article instead of news on the homepage
$page->category()->
Any idea how to do this?

Thanks

see architect or blueprint reader plugins

1 Like

This can also be done without a plugin using a category map.

In your config:

c::set('categoryMap', array(
  'news' => 'News Article',
  'architecture' => 'Architecture',
  'photography' => 'Photography',
));

In your template:

<?php
$categoryMap = c::get('categoryMap');
echo $categoryMap[trim($page->category())];
?>

Edit: You can even drive this one step further. In addition to the category map array in your config, create a custom field method in a plugin file:

<?php
field::$methods['getCategoryName'] = function($field) {
  return c::get('categoryMap')[trim($field->value)];
};

Then you can call the field like this in your template:

<?= $page->category()->getCategoryName(); ?>

And to make this complete:

In a multi-language context, you can use l::set() and l::get() instead.

2 Likes

Thanks. We did what might not be a conventional hack. We took 'News Article ’ => β€˜News Article’, We use it in one place where we echo it out. so $page->category->() then it echos out. Spaces may not be ideal, but hey, they worked for what we needed.