Select theme

Kirby CMS: automatically open external links in new tab

Published by on

It is widely known that you can open links in a new tab using target="_blank".

For external links it often makes sense to add rel="noopener noreferrer" to secure the content of the current page. More information and a demo on this topic can be found in Mathias Bynens' blog post on this topic.

You can easily add this functionality in Kirby's WYSIWYG markdown editor using the (link) tag. However in longer texts with many links, there is a chance that one might forget adding the rel attribute.

It would be much nicer if Kirby would add target="_blank" and rel="noopener noreferrer" to external links automatically when rendering a page.

For this functionality I'm using feature called hooks: It makes it possible to add custom logic in different steps of the page rendering process.

To get started I first added a new entry called kirbytext:after in confg.php under hooks:

This function is executed for each field with the type kirbytext. The HTML string generated from the markdown is passed as an argument. This function is expected to modify the HTML string and return it at the end.

To find and modify all anchor elements in this HTML string one could use a complicated regular expression.

However it is much more convienient to use the PHP DOM library instead:

Automatic bookmarks

Similarly, you can add a link with an automatically generated ID to all headings to jump easily between sections:

Comments

  • Thank you so much for that external link hook. Works really well!

Leave a comment

By submitting your data, you agree that all entered data may be saved and displayed as a comment.