How to Quickly Add Facebook Open Graph and Twitter Cards to Joomla

Joomla OpenGraphIn this article, we're going to discuss how to add Facebook Open Graph and Twitter Cards to Joomla without a plugin or module.

If you haven't been living under a rock for the past decade or so, you'll probably have very often seen people sharing articles on Facebook with a nice image and title, and a similar thing on Twitter with large pretty cards showing a large image.

The best way to control this is to implement what is called the Open Graph protocol. This is a set of tags that give hints to Twitter, Facebook, and other crawlers on what content they should use.

You can easily do this in Joomla without installing any 3rd party extension by creating a template override.

Here's how to do this:

 

Twitter Cards Joomla

When implementing Twitter cards using Joomla open graph tags - rather than having an image showing up at random, or no image at all, your Joomla article will be suggesting the best image to use.

See the below example from the CollectiveRay twitter feed.

Joomla Twitter Facebook open graph

Facebook Open Graph example

On the other hand - on Facebook, using the Joomla Open Graph tags, your posts when shared will look like the below.

Joomla Facebook Open Graph

How to Enable Joomla Open Graph tags

1. Create a Template Override for articles

Extensions > Templates > Templates > (your template) Details and Files >  Create Overrides > Components > com_content > article

Once you have created the article template override, you can add the metadata to the override which is going to be used to display your article. Essentially, you'll need to add the following content to the article such that the metadata is picked up from your article.

2. Add the metadata for Facebook / Twitter Open Graph

Go to Extensions > Templates > Templates > (your template) Details and Files > Editor > html > com_content > articles > default.php

Add the code below to the top between php tags:  <?php  (code goes here)  ?> - take a bit of care where to add this, you might break your template temporarily if you add it in the wrong place...so do take a full backup of the file, before performing any of these edits

if (isset($images->image_intro) and !empty($images->image_intro))
{
  $timage= htmlspecialchars(JURI::root().$images->image_intro);
}
elseif (isset($images->image_fulltext) and !empty($images->image_fulltext))
{
  $timage= htmlspecialchars(JURI::root().$images->image_fulltext);
}
else
{
  $timage= 'https://www.joomlawire.com/joomla3/images/joomla_logo_black.jpg';
}
$doc =& JFactory::getDocument();
$doc->addCustomTag( '
  <meta name="twitter:title" content="'.$this->escape($this->item->title).'">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:site" content="@DARTCreations">
  <meta name="twitter:creator" content="@DARTCreations">
  <meta name="twitter:url" content="'.str_replace('" ','&quot;',JURI::current()).'"="">
  <meta name="twitter:description" content="'.strip_tags($this->item->introtext).'">
  <meta name="twitter:image" content="'.$timage.'">
  <meta property="og:title" content="'.$this->escape($this->item->title).'"/>
  <meta property="og:type" content="article"/>
  <meta property="og:email" content="info@dart-creations.com";/>
  <meta property="og:url" content="'.str_replace('" ','&quot;',juri::current()).'"="">
  <meta property="og:image" content="'.$timage.'"/>
  <meta property="og:site_name" content="DARTCreations"/>
  <meta property="fb:admins" content="xxxxxxxxxxx"/>
  <meta property="og:description" content="'.strip_tags($this->item->introtext).'"/>
');

 

3. Customize the Open Graph tags to your values

The above code is customized to CollectiveRay, so obviously edit the values to the items which you want for your own site.

These are the lines you need to change:

$timage= 'https://www.joomlawire.com/joomla3/images/joomla_logo_black.jpg';

This should be the location of the default image, should your article not have an intro image, or a full text image.

  <meta name="twitter:site" content="@DARTCreations">
  <meta name="twitter:creator" content="@DARTCreations">

 

The above @ value should be changed to reflect your Twitter username.

<meta property="og:email" content="info@dart-creations.com";/>

The above email address should be updated to your own email address.

<meta property="og:site_name" content="DARTCreations"/>

The above should be updated to the name of your site.

Instead of the xxxxxxxxxxx of the fb:admins tag, you'll need to enter the numeric id of the Facebook user who will be performing such stuff as Page Insights. To find the number, you might want to look at such a tool as this tool - find my Facebook ID.

Reader suggestion:

Eddie suggested that you can restrict the length of the description to a specified number of character if you use the code below:

You might want to restrict the length of the description to c.45 characters by using mb_strimwidth or substr like this:

<meta name="twitter:description" content="'.mb_strimwidth(strip_tags($this->item->introtext),0,45).'"/>
or 
<meta property="og:description" content="'.substr(strip_tags($this->item->introtext), 0,45).'"/>

 

Ed has also made a 2nd suggestion which actually allows you to pick the data from the meta description of the article, which is a pretty great suggestion.

I've tweaked the code a little & have got the following:

<meta name="twitter:description" content="Read about our Magento website redesign an..."/>.

This is produced by this code (note ">" is stripped out):

<meta property="og:description" content="'.mb_strimwidth(strip_tags($doc->getMetaData( 'description' )),0,45, " ...").'"=""/>

You can see I'm getting the meta description, limited to 45 characters, & adding ellipsis if the description is truncated. This way I can "click bait" my description for better CTR while keeping my intro text readable in keeping with the "style" or "voice" of my website. By using the meta description I can also add some of this code to an override for categories too!

Another reader: Thomas Meredith commented below that the code

<meta property="og:url" content="'.JURI::current().'"/>



was vulnerable to XSS vulnerabilities and the correct code should be: 

<meta property="og:url" content="'.str_replace('" ','&quot;',JURI::current()).'"="">


We have updated the code with this correction, and you should do likewise.

Let's help you manage your Joomla better

joomla

Free Joomla tips ebook button

More updates from our visitors

If you follow the conversation below, you'll find that even if the above code works for most situations, there are specific instances where the code this not work. Michael from N8 Solutions, took it upon himself to make found a solution for those instances where this was not working. 

In the spirit of the open-source Joomla community, they shared the code with the rest of visitors in the comments below. I'm reproducing the code and Michael's comments verbatim, for clarity:

I was able to solve the problem not only for the "Contact" page but also for the "Blog" & "Featured" menu item pages.

First, what I wrote above for the Contact Page, for grabbing the "Name" the contact is saved as will work. The "twitter:title" & "og:title" should look like this if you want to use the saved name of the contact.

<meta name="twitter:title" content="'.$this->escape($this->item->name).'" />

However, if you would like to use the information from the menu you can do that with this new code which will also work for "Blog" & "Featured" menu item pages.
You can choose to use the "Menu Title", "Browser Page Title", or the "Page Heading". I prefer to use the Page Heading and set the menu not to show the Page Heading. This way I can utilize the Page Heading for Open Graph the way I want since it won't show up anywhere else unlike the Menu Title or the Browser Page Title which will.

To do this, you need to add the code below between "$timage" and above "$doc".

$active = JFactory::getApplication()->getMenu()->getActive();
$title = $active->title;
$browserpagetitle = $active->params->get('page_title');
$pageheading = $active->params->get('page_heading');

Then you should replace the code for "twitter:title" & "og:title" with this code below in order to use the "Page Heading".

<meta name="twitter:title" content="'.$this->escape($pageheading).'" />
<meta property="og:title" content="'.$this->escape($pageheading).'" />

If instead, you want to use the "Menu Title" or the "Browser Page Title", in the code you would replace "$pageheading" with either "$title" to use the Menu Title or "$browserpagetitle" to use the Browser Page Title.

You can create the overrides here:
Create Overrides > Components > com_content > category
Create Overrides > Components > com_content > featured
Create Overrides > Components > com_contact > contact

Then edit the overrides, adding the code above, in their respective locations:
Editor > html > com_content > category > blog.php
Editor > html > com_content > featured > default.php
Editor > html > com_contact > contact > default.php

I also removed the "if" statement for the Open Graph Image leaving only the basic line:

$timage= 'https://www.domain.com/custom-open-graph-image.jpg';

I did this because the "if" statement is not necessary for these pages since there is no Intro Image or Full Text image.

Another thing of importance concerning the "Descriptions".

For CONTACTS:


In the code for the contact page for the "twitter:description" & "og:description" the "introtext" needs to be replaced with "metadesc" in order to grab the Meta Description that is set for the contact. If you do not set a description for the contact then nothing will be displayed for the open graph description tags.

For BLOG & FEATURED Articles:
Just as above for the contacts the "twitter:description" & "og:description" the "introtext" needs to be replaced with Eddie's code above in order to grab the Meta Description that is set for either the Blog or Featured Article Menu Item. Again, if you do not set a description there then nothing will be displayed. So you don't have to look for it, here is the code Eddie provided above and what the description lines should look like.

<meta name="twitter:description" content="'.mb_strimwidth(strip_tags($doc->getMetaData( 'description' )),0,45, " ...").'" />
<meta property="og:description" content="'.mb_strimwidth(strip_tags($doc->getMetaData( 'description' )),0,45, " ...").'" />

I prefer to change the character length from 45 to 160 since I'm not interested in "Bait Clicking" potential site visitors.

I hope this is helpful to others!

 

4. Test against the Twitter validator and the Facebook Linter 

Check the article on your website against the Twitter validator: https://cards-dev.twitter.com/validator 

and the

Facebook Linter:  https://developers.facebook.com/tools/debug/

And that's how you add Open Graph metadata to your Joomla articles :)

Frequently Asked Questions

What is the Open Graph Protocol?

The Open Graph protocol is a way to allow websites to control what content is shown when their website content is shared on Facebook, Twitter, or other platforms that are Open Graph friendly. If your website does not use these tags, the platform can decide what image to show, and will probably show an unrelated image.

Does Google use Open Graph?

No Google does not use the Open Graph protocol for the search engine result pages. Instead, it uses Structured Data, which is another method to allow crawlers to better understand the content on your website. Even though Google does not use OG tags per se, traffic to your website is a ranking signal, so it will probably benefit your organic rankings to have a social-media friendly website.

How do you set Open Graph tags in Joomla?

To set open graph tags in Joomla you can use a template override and populate the tags from the content of your articles as we have described in the article above. Alternatively, you can install a plugin that is able to generate these tags automatically from your website content.

How do you check Open Graph tags?

To check Open Graph tags, you can either use the Facebook Linter or Sharing Debugger, or use the Twitter card validator.

About the Author
David Attard
David has been working in or around the online / digital industry for the last 18 years. He has vast experience in the software and web design industries using WordPress, Joomla and niches surrounding them. As a digital consultant, his focus is on helping businesses get a competitive advantage using a combination of their website and digital platforms available today.

One more thing... Did you know that people who share useful stuff like this post look AWESOME too? ;-)
Please leave a useful comment with your thoughts, then share this on your Facebook group(s) who would find this useful and let's reap the benefits together. Thank you for sharing and being nice!

Disclosure: This page may contain links to external sites for products which we love and wholeheartedly recommend. If you buy products we suggest, we may earn a referral fee. Such fees do not influence our recommendations and we do not accept payments for positive reviews.

 

who are we?

CollectiveRay is run by David Attard - working in and around the web design niche for more than 12 years, we provide actionable tips for people who work with and on websites. We also run DronesBuy.net - a website for drone hobbyists.

David attard

 

 

Author(s) Featured On:  Inc Magazine Logo   Sitepoint logo   CSS Tricks logo    webdesignerdepot logo   WPMU DEV logo   and many more ...