Generate Open Graph and Twitter meta tags in WordPress without a plugin.
Open Graph and Twitter Cards enable any web page to become a rich object in a social graph. These metadata promote your blog posts with attractive images, titles, and descriptions and attract new readers and potential customers to your website.
Assuredly, every user has continued support for metatags on their websites or blogs. Difficulties transpire for WordPress users when they have to use different plugins for this very simple task. No doubt WordPress plugins make one’s life easy by just clickety-click installation and setup. But at the backend, these plugins bloat your blog posts and make them buggy or slow – I mean real slow!
For WordPress users, I would urge them not to use any plugin merely to append Open Graph and Twitter meta tags to their blog articles. It’s not a good practice. The best way to go is to create your function to generate essential metadata/metatags.
Let’s dive right into it and create a custom function named gen_automatic_metadata() (you can name it whatever you wish) within the functions.php file which would automatically generate Open Graph and Twitter Cards including General Meta Tags for the individual blog post.
Common Meta Tags
Let’s first set the following meta tags common to our function.
charset – specifies the character encoding for the HTML document.
viewport – gives the browser instructions to control the page’s dimensions and scaling.
fb:app_id – allow FB to associate the URL Open Graph with an application.
Open Graph & Twitter Card for Single Post
Above we have appended the three main common meta tags. Now we will code dynamic Open Graph & Twitter Card tags specifically for single posts/articles.
If you want to dive deep into Open Graph & Twitter Cards follow the below links.
If a user shares a link to the main blog page, category page, or search page from your website, we need to generate a new set of meta tags for those pages.
We would do that in an else statement of your function.
Final Code
Below is the complete gen_automatic_metadata() function.
That’s all you need to do. As soon as you save your functions.php file it will start showing all the metadata in the <head> tag. To validate your metadata use Sharing Debugger & Twitter Card Validator.
I hope this article helped you add Open Graph & Twitter Card to your website in a more efficient manner. You can edit this function to make it more robust and add more meta tags as per requirement.
If you liked this article, then please like and share. Also, feel free to drop your details below if you require any assistance with your project to add this script.