Custom metatags

The first file you will find, when you take a look at Kirby's content folder is site.txt. It is there to store global content for your site, such as the main title or additional values, which are used for your site's metatags – keywords, description, etc. Basically you can store everything in there, which you might need on multiple pages but you don't want to hard-wire into your templates.

But especially with things like the keywords and description metatags, you might want to overwrite those global values on any page later. For example if you are building your portfolio it would be cool to have custom keywords and description in your metatags for each project.

The content file

Let's say there's a project.txt stored in projects/my-first-project and it has a title and text field so far. What you need to do is to add a description and keywords field.

Title: My first project
----
Text: This is a great project I did some years ago
----
Description: Custom description used in the metatags
----
Keywords: custom, keyword, list, for, my, first, project
----

The header snippet

Go to site/snippets/header.php By default it looks like this, but I guess you already changed that.

What we want here is to check for custom description and keywords for the current page and replace the global values from site.txt, if custom values are available.

…

<?php if($page->description() != ''): ?>
<meta name="description" content="<?php echo html($page->description()) ?>" />
<?php else: ?>
<meta name="description" content="<?php echo html($site->description()) ?>" />
<?php endif ?>

<?php if($page->keywords() != ''): ?>
<meta name="keywords" content="<?php echo html($page->keywords()) ?>" />
<?php else: ?>
<meta name="keywords" content="<?php echo html($site->keywords()) ?>" />
<?php endif ?>

…

You can use those kind of checks for any metatags or any other part of your site, which you might want to keep overwritable. The cool thing is that you don't even have to add a keyword or description field to any content file. If it is there and you've added some text to it, it will be used and if it is not there or it is empty it will be ignored.

blog comments powered by Disqus