Have you ever wondered why some links when shared on social media have a link preview and some do not? The magic behind this is the Open Graph protocol, and this recipe provides a boilerplate to easily create OG images for your Kirby website with content representations.
The Open Graph protocol was originally created by Meta (formerly Facebook). The protocol enables any web page to become a rich object in a social graph. For instance, this is used on Social Media to standardize the use of metadata within a webpage to represent the content of a page.
The basic HTML markup within the
<head> element looks like the following:
The code snippet above is the same as the one that used for this cookbook recipe, and when you share it on social media, the link preview will look something like this:
While the above example works great on the Kirby CMS website with a custom plugin (check it out on GitHub), a simplified approach is to use content representations to generate these OG images. This approach works well if you only need custom OG images for a single page type.
There is a great guide about content representations you should check out first.
Using content representations for OG image generation will only work if you use a dedicated template, e.g. for your blog articles.
See the templates guide in case you are not familar with templates yet.
In case you are already using template files and your filesystem looks like the example above you are good to go!
First, create a new content representations template file, e.g.
article.png.php. This allows you to create various OG images with
.png extension for the given template.
There are tons of possibilities now to create and manipulate images with PHP. Check out the GD and Image Functions of PHP. The only limit is your creativity!
- Let's start with defining the canvas size for the image:
The recommended aspect ratio for an OG image is 1.91:1, but many tutorials out there refer to a format of 1200x630 pixels. However, 1200x628 yields a closer aspect ratio and is therefore preferred.
- Define some variables, e.g. for colors or fonts:
- Set the background color:
- Print the page title to the image:
- Finally, return the
The basic OG image using only text will look like this:
For example, a colored rectangle:
And a logo:
Make sure that all paths to fonts and files as well as fieldnames used actually exist in your installation, otherwise this will not work as expected.