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

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