Automatic Opengraph Image

1.3k views Asked by At

When sharing a page on Facebook or other social network:

  1. If <meta property="og:image" content="http://url.to/image.jpg" /> is present, it is used to generate a thumbnail. That's ok.

  2. If <meta property="og:image"> is not present but there is an image on the page, the first image present on the HTML page is used as thumbnail. This is good as well.

  3. If <meta property="og:image"> is not present and there is no image on the page, then there is no thumbnail.

How to give a default thumbnail image with <meta property="og:image">, that will be used if and only if we are in case #3?

i.e. : this default image will be used only if there is no image on the page (if there is one, this image will be used instead!)


More generally, is there a way to tell:

"If there is no og:image, use the page rendering as thumbnail (like would do the well-known http://netrenderer.com/)"


What do I want to achieve: always have a thumbnail, regardless there is an image on the page or not.

2

There are 2 answers

0
Sebastian G. Marinescu On BEST ANSWER

As far as I understand, you want to provide a fallback og:image-tag, if there is no image on the page to choose from.

I see two general solutions:

  • Post-Check the page afterwards with JavaScript and append the fallback og:image-tag if no images are present (possibly not reliable enough)
  • Pre-Check your content in your Backend-Parser (PHP-Controller) and deliver the response with the og:image-tag if necessary

I'm recommending to do this in the Backend.

Let's assume you have a single-file PHP-controller, where you mix logic, data and view together... And let's say you have all your content stored in a variable, maybe called $pagecontent.

If this variable would hold all upcoming content as a string, you could do something like the following inside your html-head:

<head>
  <!-- other code -->
  <?php 
    if (strpos($pagecontent, '<img ') === false) {
      echo '<meta property="og:image" content="http://url.to/fallback-image.jpg" />';
    }
  ?>
</head>

I hope this helps.

2
Buzz On

If you want always a thumbnail image by your choice to be present, than you need for the case #3 provide a default image:

<meta property="og:image" content="http://YOUR_DOMAIN.COM/YOUR_DEFAULT_image.jpg" />

otherwise Facebook will add or ignore image by its own decision