OpenGraph, or social media embeds are how your site appears when someone links to it. You normally have an image you want to show as part of this, but wouldn’t it be awesome to have a unique image with the tile of the page on every page on your site, like below?
If you are running your site on your own hosting, and can run PHP I have created a script to do this for you - completely customisable!
Follow the steps below, or watch the video.
- First copy the code from here
- Save the code into a file and call it gen.php
- Once downloaded, there are a couple settings you need to set.
- First you shall need to create a background image, and save it somewhere.
the image should be 1200 x 630 pixels in size. Its ok if your image is a little bigger or smaller, the script will make sure it is the correct size. Leave space in the center of the image for the page title to go! The image must be a PNG.
- You can now choose the font you want the text to be rendered in, first choose a font from Google Fonts, then download it locally. Then use this website to convert it to TTF format.
Your font must be a TTF format.
- Now you have your background image, and font you can now setup the script.
- In your websites main folder, where the webpages are saved upload the script into its own folder, name this how you want.
- Inside this same folder, upload your background and font files.
- Open the Gen.php file and under the variables at the top of the page, modify these with the locations of you files.
For $imageURL, use the full path to the background image, for example
https://example.com/opengraph/background.png. For $font you should be able to just specify
./YourFontName.ttfbut if this does not work, use the exact path to the font on your server. Contact your host if you do not know the exact path.
- Next make another folder inside where the script is saved, call this
generatedfolder is used to cache already generated images, if an image has already been generated the script will serve these automatically instead of making a new image. Images in this folder older than 1 minute are deleted automatically.
- The script is now setup, to use it in your HTML pages simply open a file and in the meta data of
twitter:imagelink to the location of the gen.php script, appending to the end of the link
=insert the title you want to show.
<meta name="twitter:image" content="https://example.com/opengraph/gen.php?title=Webpage%20Title">
<meta property="og:image" content="https://example.com/opengraph/gen.php?title=Webpage520Title">
Remember, you must use URL encoding, spaces become
%20use this site to convert text to URL encoding.
- You have now setup your site to generate custom social media embed images! Hopefully this is useful and saves you time.
Any questions, or issues please comment below. Remember that you must have hosting that lets you run PHP V7+ - this is not possible on the Bootstrap Studio Hosting.